/**
 * 매매 신호 패널
 * - 백테스트 결과
 * - 매매 신호 테이블
 * - 수익률 요약
 * 
 * React.memo로 최적화
 */

import React from 'react';
import { Box, Paper, Typography, Chip } from '@mui/material';
import type { BacktestResult } from '../../services/backtestApi';

// TradeSimulation 타입 정의 (SignalTable에서 가져오지 않고 여기서 정의)
export interface TradeSimulation {
  date: string;
  timestamp?: string;
  signal: string;
  price: number;
  quantity: number;
  tradeAmount: number;
  commission: number;
  netAmount: number;
  holdingQty: number;
  avgBuyPrice: number;
  profitLoss: number;
  profitLossRate: number;
  totalAsset: number;
}

export interface SignalPanelProps {
  backtestResult: BacktestResult | null;
  tradeSimulations: TradeSimulation[];
  timeInterval: string;
  loading?: boolean;
  onSignalClick?: (signal: any) => void;
}

const SignalPanel: React.FC<SignalPanelProps> = (props) => {
  const {
    backtestResult,
    tradeSimulations,
    timeInterval,
    loading = false,
    onSignalClick,
  } = props;

  console.log(`📊 [SignalPanel] 렌더링: ${tradeSimulations.length}개 신호`);

  if (!backtestResult) {
    return null;
  }

  const {
    returnRate,
    winRate,
    totalTrades,
    winningTrades,
    losingTrades,
  } = backtestResult;

  return (
    <Paper
      elevation={2}
      sx={{
        p: 2,
        bgcolor: 'background.paper',
      }}
    >
      {/* 요약 정보 */}
      <Box sx={{ mb: 2, display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'center' }}>
        <Typography variant="h6">백테스트 결과</Typography>
        
        <Chip
          label={`수익률: ${(returnRate * 100).toFixed(2)}%`}
          color={returnRate >= 0 ? 'success' : 'error'}
          size="small"
        />
        
        <Chip
          label={`승률: ${(winRate * 100).toFixed(1)}%`}
          color="primary"
          size="small"
        />
        
        <Chip
          label={`총 거래: ${totalTrades}회`}
          size="small"
        />
        
        <Chip
          label={`수익: ${winningTrades}회`}
          color="success"
          variant="outlined"
          size="small"
        />
        
        <Chip
          label={`손실: ${losingTrades}회`}
          color="error"
          variant="outlined"
          size="small"
        />
      </Box>

      {/* TODO: 매매 신호 테이블 - SignalTable이 MacdResult[]를 기대하지만 TradeSimulation[]를 받고 있음. 별도 컴포넌트 필요 */}
      {tradeSimulations.length > 0 && (
        <Box sx={{ mt: 2 }}>
          <Typography variant="body2" color="text.secondary">
            {tradeSimulations.length}개의 거래 신호
          </Typography>
        </Box>
      )}
    </Paper>
  );
};

export default React.memo(SignalPanel, (prevProps, nextProps) => {
  return (
    prevProps.backtestResult === nextProps.backtestResult &&
    prevProps.tradeSimulations === nextProps.tradeSimulations &&
    prevProps.timeInterval === nextProps.timeInterval &&
    prevProps.loading === nextProps.loading
  );
});
