import React, { useMemo } from 'react';
import { getKoreanName } from '../../utils/marketNameCache';
import type { StrategyDto } from '../../utils/backendApi';
import type { VirtualIndicatorSnapshot } from '../../hooks/useVirtualIndicatorSnapshots';
import { useLiveReceiveFlash } from '../../hooks/useLiveReceiveFlash';
import type { ChartRealtimeSource } from '../../hooks/useChartRealtimeData';
import { buildConditionMetrics, resolveVirtualTradeTiming } from '../../utils/virtualSignalMetrics';
import VirtualLiveBadge from './VirtualLiveBadge';
import type { VirtualLiveStatus } from '../../hooks/useVirtualTargetLiveStatus';
import type { VirtualCardViewMode } from '../../utils/virtualTradingStorage';
import VirtualTargetCardChart from './VirtualTargetCardChart';
import VirtualTargetSignalPanel from './VirtualTargetSignalPanel';
import type { Theme } from '../../types';
import type { TickerData } from '../../hooks/useMarketTicker';
import VirtualTargetQuote from './VirtualTargetQuote';

export type VirtualCardDisplayMode = 'signal' | 'chart';

interface Props {
  market: string;
  strategy: StrategyDto | undefined;
  strategies: StrategyDto[];
  strategyId: number | null;
  globalStrategyId: number | null;
  onStrategyChange?: (strategyId: number | null) => void;
  snapshot: VirtualIndicatorSnapshot | undefined;
  running: boolean;
  liveStatus?: VirtualLiveStatus;
  lastTickAt?: number;
  viewMode?: VirtualCardViewMode;
  displayMode?: VirtualCardDisplayMode;
  onDisplayModeChange?: (mode: VirtualCardDisplayMode) => void;
  onEnterFocus?: () => void;
  selected?: boolean;
  onSelect?: () => void;
  theme?: Theme;
  chartRealtimeSource?: ChartRealtimeSource;
  chartSeriesPriceLabels?: boolean;
  ticker?: TickerData;
}

const VirtualTargetCard: React.FC<Props> = ({
  market,
  strategy,
  strategies,
  strategyId,
  globalStrategyId,
  onStrategyChange,
  snapshot,
  running,
  liveStatus = 'idle',
  lastTickAt,
  viewMode = 'summary',
  displayMode = 'signal',
  onDisplayModeChange,
  onEnterFocus,
  selected = false,
  onSelect,
  theme = 'dark',
  chartRealtimeSource = 'BACKEND_STOMP',
  chartSeriesPriceLabels = true,
  ticker,
}) => {
  const ko = getKoreanName(market);
  const sym = market.replace(/^KRW-/, '');
  const tf = snapshot?.timeframe ?? '—';
  const rows = snapshot?.rows ?? [];

  const metrics = useMemo(() => buildConditionMetrics(rows), [rows]);
  const tradeTiming = useMemo(() => resolveVirtualTradeTiming(metrics), [metrics]);
  const metCount = metrics.filter(m => m.status === 'match').length;
  const evalCount = metrics.filter(m => m.status !== 'unknown').length;

  const isDetail = viewMode === 'detail';
  const isChart = displayMode === 'chart';

  const receiveSignal = useMemo(() => {
    if (!running || isChart) return null;
    return `${lastTickAt ?? 0}|${snapshot?.updatedAt ?? 0}`;
  }, [running, lastTickAt, snapshot?.updatedAt, isChart]);
  const receiving = useLiveReceiveFlash(receiveSignal, running && !isChart);

  return (
    <div
      className={[
        'vtd-card',
        'vtd-card--signal',
        running ? 'vtd-card--live' : '',
        receiving ? 'vtd-card--receiving' : '',
        isDetail ? 'vtd-card--detail' : 'vtd-card--summary',
        isChart ? 'vtd-card--chart-mode' : '',
        selected ? 'vtd-card--selected' : '',
        tradeTiming === 'buy' ? 'vtd-card--timing-buy' : '',
        tradeTiming === 'sell' ? 'vtd-card--timing-sell' : '',
      ].filter(Boolean).join(' ')}
      onClick={onSelect}
      onKeyDown={e => {
        if (onSelect && (e.key === 'Enter' || e.key === ' ')) {
          e.preventDefault();
          onSelect();
        }
      }}
      role={onSelect ? 'button' : undefined}
      tabIndex={onSelect ? 0 : undefined}
      aria-pressed={onSelect ? selected : undefined}
    >
      <div className="vtd-card-head">
        <div className="vtd-card-head-main">
          <div className="vtd-card-title">
            <span className="vtd-card-ko">{ko}</span>
            <span className="vtd-card-sym">{sym}</span>
          </div>
          <label className="vtd-card-strategy-field" onClick={e => e.stopPropagation()}>
            <span className="vtd-card-strategy-label">투자전략</span>
            <select
              className="vtd-card-strategy-select"
              value={strategyId ?? globalStrategyId ?? ''}
              onChange={e => {
                const v = e.target.value;
                onStrategyChange?.(v ? Number(v) : null);
              }}
            >
              <option value="">— 선택 —</option>
              {strategies.map(s => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>
          </label>
          <span className="vtd-card-tf">시간봉 {tf}</span>
        </div>
        <div className="vtd-card-head-actions">
          {onEnterFocus && (
            <button
              type="button"
              className="vtd-card-focus-btn"
              onClick={e => { e.stopPropagation(); onEnterFocus(); }}
              title="전체화면 보기 (차트 + 신호)"
              aria-label="전체화면 보기"
            >
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
                <polyline points="5,1 1,1 1,5" />
                <polyline points="9,13 13,13 13,9" />
                <line x1="1" y1="1" x2="6" y2="6" />
                <line x1="13" y1="13" x2="8" y2="8" />
              </svg>
            </button>
          )}
          <div className="vtd-card-mode-toggle" role="group" aria-label="이 종목 표시" onClick={e => e.stopPropagation()}>
            <button
              type="button"
              className={`vtd-card-mode-btn${displayMode === 'signal' ? ' vtd-card-mode-btn--on' : ''}`}
              onClick={() => onDisplayModeChange?.('signal')}
              title="이 종목만 신호 보기"
            >
              신호
            </button>
            <button
              type="button"
              className={`vtd-card-mode-btn${displayMode === 'chart' ? ' vtd-card-mode-btn--on' : ''}`}
              onClick={() => onDisplayModeChange?.('chart')}
              title="이 종목만 차트 보기"
            >
              차트
            </button>
          </div>
        </div>
      </div>

      <div className="vtd-card-meta">
        <VirtualTargetQuote market={market} ticker={ticker} compact />
        {!isChart && isDetail && evalCount > 0 && (
          <span className="vtd-card-met-count">{metCount}/{evalCount} 조건 충족</span>
        )}
        {running && <VirtualLiveBadge status={liveStatus} receiving={receiving} />}
      </div>

      {isChart ? (
        <VirtualTargetCardChart
          market={market}
          strategy={strategy}
          theme={theme}
          running={running}
          chartRealtimeSource={chartRealtimeSource}
          chartSeriesPriceLabels={chartSeriesPriceLabels}
        />
      ) : (
        <VirtualTargetSignalPanel
          snapshot={snapshot}
          viewMode={viewMode}
          receiving={receiving}
        />
      )}
    </div>
  );
};

export default VirtualTargetCard;
