import React, { useMemo } from 'react';
import type { VirtualIndicatorSnapshot } from '../../hooks/useVirtualIndicatorSnapshots';
import {
  buildConditionMetrics,
  computeMatchRate,
  getTrafficLightState,
} from '../../utils/virtualSignalMetrics';
import VirtualSignalEqualizer from './VirtualSignalEqualizer';
import VirtualSignalTrafficLight from './VirtualSignalTrafficLight';
import VirtualConditionList from './VirtualConditionList';
import VirtualIndicatorCompareTable from './VirtualIndicatorCompareTable';
import type { VirtualCardViewMode } from '../../utils/virtualTradingStorage';

interface Props {
  snapshot: VirtualIndicatorSnapshot | undefined;
  viewMode?: VirtualCardViewMode;
  receiving?: boolean;
  className?: string;
}

const VirtualTargetSignalPanel: React.FC<Props> = ({
  snapshot,
  viewMode = 'summary',
  receiving = false,
  className = '',
}) => {
  const rows = snapshot?.rows ?? [];
  const isDetail = viewMode === 'detail';

  const metrics = useMemo(() => buildConditionMetrics(rows), [rows]);
  const matchRate = useMemo(
    () => computeMatchRate(metrics, snapshot?.matchRate),
    [metrics, snapshot?.matchRate],
  );
  const trafficState = useMemo(() => getTrafficLightState(matchRate, metrics), [matchRate, metrics]);

  if (rows.length === 0) {
    return (
      <p className={`vtd-muted vtd-card-empty${className ? ` ${className}` : ''}`}>
        전략 조건·지표 데이터 없음
      </p>
    );
  }

  return (
    <div
      className={[
        'vtd-sig-panel-wrap',
        isDetail ? 'vtd-sig-panel-wrap--detail' : 'vtd-sig-panel-wrap--summary',
        receiving ? 'vtd-sig-panel-wrap--receiving' : '',
        className,
      ].filter(Boolean).join(' ')}
    >
      <div className={`vtd-sig-panel${isDetail ? ' vtd-sig-panel--detail-top' : ' vtd-sig-panel--summary'}`}>
        <div className="vtd-sig-panel-title">SIGNAL INTELLIGENCE &amp; MATCH RATES</div>
        <div className="vtd-sig-visual">
          <div className="vtd-sig-visual-eq">
            <VirtualSignalEqualizer matchRate={matchRate} />
          </div>
          <VirtualConditionList metrics={metrics} />
          <VirtualSignalTrafficLight state={trafficState} matchRate={matchRate} />
        </div>
      </div>
      {isDetail && (
        <div className="vtd-sig-detail-table" aria-label="지표별 상태 목록">
          <VirtualIndicatorCompareTable metrics={metrics} />
        </div>
      )}
    </div>
  );
};

export default VirtualTargetSignalPanel;
