/**
 * 매매 시그널 알림 목록 화면
 */
import React, { useCallback } from 'react';
import type { Theme } from '../types';
import { useTradeNotification, type TradeNotificationItem } from '../contexts/TradeNotificationContext';
import { buildSignalDetailRows, formatSignalPrice, getSignalHeadline } from '../utils/tradeSignalDisplay';

interface Props {
  theme: Theme;
  onGoToChart: (market: string) => void;
}


export const TradeNotificationListPage: React.FC<Props> = ({ theme, onGoToChart }) => {
  const {
    allNotifications,
    unreadCount,
    markAsRead,
    markAllAsRead,
    openDetail,
    refreshHistory,
  } = useTradeNotification();

  const [filter, setFilter] = React.useState<'all' | 'unread'>('all');

  const filtered = filter === 'unread'
    ? allNotifications.filter(n => !n.isRead)
    : allNotifications;

  const handleRow = useCallback((item: TradeNotificationItem) => {
    if (!item.isRead) markAsRead(item.id);
    openDetail(item, { centered: true });
  }, [markAsRead, openDetail]);

  return (
    <div className={`tnl-page app ${theme}`}>
      <div className="tnl-header">
        <h1 className="tnl-title">매매 시그널 알림</h1>
        <p className="tnl-sub">
          실시간 전략 실행 시 발생한 BUY/SELL 신호입니다. 화면·종목과 무관하게 수신됩니다.
        </p>
        <div className="tnl-toolbar">
          <span className="tnl-chip tnl-chip--warn">미확인 {unreadCount}건</span>
          <div className="tnl-filter">
            <button
              type="button"
              className={filter === 'all' ? 'tnl-filter-btn--active' : ''}
              onClick={() => setFilter('all')}
            >
              전체
            </button>
            <button
              type="button"
              className={filter === 'unread' ? 'tnl-filter-btn--active' : ''}
              onClick={() => setFilter('unread')}
            >
              미확인
            </button>
          </div>
          <button type="button" className="tnl-btn" onClick={() => void refreshHistory()}>
            새로고침
          </button>
          {unreadCount > 0 && (
            <button type="button" className="tnl-btn tnl-btn--primary" onClick={markAllAsRead}>
              모두 읽음
            </button>
          )}
        </div>
      </div>

      <div className="tnl-list-wrap">
        {filtered.length === 0 ? (
          <div className="tnl-empty">표시할 알림이 없습니다.</div>
        ) : (
          <ul className="tnl-list">
            {filtered.map(item => {
              const isBuy = item.signalType === 'BUY';
              const detailRows = buildSignalDetailRows(item);
              return (
                <li
                  key={item.id}
                  className={`tnl-row ${!item.isRead ? 'tnl-row--unread' : ''}`}
                >
                  <button
                    type="button"
                    className="tnl-row-main"
                    onClick={() => handleRow(item)}
                  >
                    <span className={`tnl-signal ${isBuy ? 'tnl-signal--buy' : 'tnl-signal--sell'}`}>
                      {item.signalType}
                    </span>
                    <span className="tnl-row-body">
                      <span className="tnl-row-title">{getSignalHeadline(item)}</span>
                      <span className="tnl-row-price">{formatSignalPrice(item.price)}</span>
                      <span className="tnl-row-detail-grid">
                        {detailRows.map(row => (
                          <span key={row.label} className="tnl-row-detail-item">
                            <span className="tnl-row-detail-lbl">{row.label}</span>
                            <span className="tnl-row-detail-val">{row.value}</span>
                          </span>
                        ))}
                      </span>
                    </span>
                    {!item.isRead && <span className="tnl-dot" aria-hidden />}
                  </button>
                  <button
                    type="button"
                    className="tnl-row-chart"
                    title="차트로 이동"
                    onClick={() => {
                      markAsRead(item.id);
                      onGoToChart(item.market);
                    }}
                  >
                    차트
                  </button>
                </li>
              );
            })}
          </ul>
        )}
      </div>
    </div>
  );
};

export default TradeNotificationListPage;
