import React, { useEffect, useState } from 'react';
import {
  loadStrategies,
  loadLiveStrategySettings,
  type LiveStrategySettingsDto,
  type PaperSummaryDto,
  type StrategyDto,
} from '../../utils/backendApi';
import { loadVirtualSession } from '../../utils/virtualTradingStorage';
import { fmtKrw } from '../TradeOrderPanel';
import PaperSplitPanel from './PaperSplitPanel';

interface Props {
  market: string;
  summary: PaperSummaryDto | null;
  paperAutoTradeEnabled?: boolean;
  onMarketSelect?: (market: string) => void;
}

const PaperLeftStrategyTab: React.FC<Props> = ({
  market,
  summary,
  paperAutoTradeEnabled = false,
  onMarketSelect,
}) => {
  const [strategies, setStrategies] = useState<StrategyDto[]>([]);
  const [settings, setSettings] = useState<LiveStrategySettingsDto | null>(null);
  const [virtualRunning, setVirtualRunning] = useState(() => loadVirtualSession().running);

  useEffect(() => {
    loadStrategies().then(setStrategies).catch(() => setStrategies([]));
  }, []);

  useEffect(() => {
    const refreshVirtual = () => setVirtualRunning(loadVirtualSession().running);
    window.addEventListener('gc_virtual_session_changed', refreshVirtual);
    window.addEventListener('storage', refreshVirtual);
    return () => {
      window.removeEventListener('gc_virtual_session_changed', refreshVirtual);
      window.removeEventListener('storage', refreshVirtual);
    };
  }, []);

  useEffect(() => {
    let cancelled = false;
    loadLiveStrategySettings(market)
      .then(s => { if (!cancelled) setSettings(s); })
      .catch(() => {
        if (!cancelled) {
          setSettings({
            market,
            strategyId: null,
            isLiveCheck: false,
            executionType: 'CANDLE_CLOSE',
            positionMode: 'LONG_ONLY',
          });
        }
      });
    return () => { cancelled = true; };
  }, [market, virtualRunning]);

  const selected = strategies.find(s => s.id === settings?.strategyId);
  const execLabel = settings?.executionType === 'REALTIME_TICK' ? '실시간 틱 (3초)' : '봉 마감 직후';

  const top = (
    <>
      <div className="ptd-asset-inline">
        <div className="ptd-asset-total ptd-asset-total--sm">
          {summary ? fmtKrw(summary.totalAsset) : '—'} <span>KRW</span>
        </div>
        <div className={`ptd-asset-ret ptd-asset-ret--sm ${(summary?.totalReturnPct ?? 0) >= 0 ? 'up' : 'down'}`}>
          {summary ? `${(summary.totalReturnPct ?? 0) >= 0 ? '+' : ''}${summary.totalReturnPct.toFixed(2)}%` : '—'}
        </div>
      </div>
      <div className="ptd-left-section">
        <p className="ptd-left-hint">
          실시간 전략·체크 대상 종목은 <strong>가상투자</strong> 화면에서 설정합니다.
          {virtualRunning ? ' (세션 실행 중)' : ''}
        </p>
        {settings?.isLiveCheck && selected && (
          <p className="ptd-left-hint">
            {market.replace(/^KRW-/, '')}: {selected.name} · {execLabel}
          </p>
        )}
      </div>
      <p className={`ptd-left-status ${paperAutoTradeEnabled ? 'ptd-left-status--on' : ''}`}>
        {paperAutoTradeEnabled
          ? '자동매매 ON — 가상투자 Match 시 가상 계좌 자동 체결'
          : '자동매매 OFF — 가상투자 타이틀바에서 변경'}
      </p>
    </>
  );

  const bottom = (
    <table className="ptd-table ptd-table--compact">
      <thead>
        <tr><th>자산</th><th>수량</th><th>손익</th></tr>
      </thead>
      <tbody>
        {(summary?.positions ?? []).length === 0 ? (
          <tr><td colSpan={3} className="ptd-muted">보유 없음</td></tr>
        ) : summary!.positions.map(p => {
          const code = p.symbol.replace(/^KRW-/, '');
          const up = (p.profitLoss ?? 0) >= 0;
          return (
            <tr
              key={p.symbol}
              className={market === p.symbol ? 'ptd-row--sel' : ''}
              onClick={() => onMarketSelect?.(p.symbol)}
            >
              <td>{code}</td>
              <td>{p.quantity.toFixed(4)}</td>
              <td className={up ? 'up' : 'down'}>
                {p.profitLoss != null ? `${up ? '+' : ''}${fmtKrw(p.profitLoss)}` : '—'}
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );

  return (
    <PaperSplitPanel
      className="ptd-split-panel--left"
      topTitle="전략 · 자산"
      bottomTitle="보유 종목"
      top={top}
      bottom={bottom}
    />
  );
};

export default PaperLeftStrategyTab;
