import React, { useState, useMemo } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
  Typography,
  Box,
  TablePagination,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Tooltip,
} from '@mui/material';
import { MacdResult } from '../types/stock';
import dayjs from 'dayjs';

interface SignalTableProps {
  data: MacdResult[];
  title?: string;
  interval?: string; // 시간 간격
  initialCapital?: number; // 초기 투자금 (기본 1000만원)
  commissionRate?: number; // 수수료율 (기본 0.05%)
  onRowClick?: (row: MacdResult, simulation?: TradeSimulation) => void; // 행 클릭 핸들러
}

// 거래 시뮬레이션 결과 타입 (export)
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;      // 총자산
  macdData: MacdResult;    // 원본 데이터
}

const SignalTable: React.FC<SignalTableProps> = ({ 
  data, 
  title = '매매 신호', 
  interval = '1d',
  initialCapital = 10000000,
  commissionRate = 0.0005,
  onRowClick,
}) => {
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [signalFilter, setSignalFilter] = useState<string>('TRADES'); // 기본값을 거래만으로 변경

  // 거래 시뮬레이션 계산
  const tradeSimulations = useMemo((): TradeSimulation[] => {
    const simulations: TradeSimulation[] = [];
    let cash = initialCapital;
    let holdingQty = 0;
    let avgBuyPrice = 0;
    let totalBuyCost = 0;

    // 시간순으로 정렬
    const sortedData = [...data].sort((a, b) => {
      const dateA = a.timestamp || a.date;
      const dateB = b.timestamp || b.date;
      return new Date(dateA).getTime() - new Date(dateB).getTime();
    });

    for (const item of sortedData) {
      if (item.signal !== 'BUY' && item.signal !== 'SELL') continue;

      const price = item.close;
      
      if (item.signal === 'BUY' && cash > 0) {
        // 매수: 가용 현금의 95%로 매수 (여유분 확보)
        const availableCash = cash * 0.95;
        const rawQuantity = availableCash / price;
        const quantity = Math.floor(rawQuantity * 100000000) / 100000000; // 암호화폐는 소수점 8자리까지
        
        if (quantity > 0) {
          const tradeAmount = quantity * price;
          const commission = tradeAmount * commissionRate;
          const netAmount = tradeAmount + commission;
          
          // 보유 정보 업데이트
          totalBuyCost += netAmount;
          holdingQty += quantity;
          avgBuyPrice = holdingQty > 0 ? totalBuyCost / holdingQty : 0;
          cash -= netAmount;
          
          simulations.push({
            date: item.date,
            timestamp: item.timestamp,
            signal: 'BUY',
            price,
            quantity,
            tradeAmount,
            commission,
            netAmount,
            holdingQty,
            avgBuyPrice,
            profitLoss: 0,
            profitLossRate: 0,
            totalAsset: cash + (holdingQty * price),
            macdData: item,
          });
        }
      } else if (item.signal === 'SELL' && holdingQty > 0) {
        // 매도: 전량 매도
        const quantity = holdingQty;
        const tradeAmount = quantity * price;
        const commission = tradeAmount * commissionRate;
        const netAmount = tradeAmount - commission;
        
        // 손익 계산
        const profitLoss = netAmount - totalBuyCost;
        const profitLossRate = totalBuyCost > 0 ? (profitLoss / totalBuyCost) * 100 : 0;
        
        cash += netAmount;
        
        simulations.push({
          date: item.date,
          timestamp: item.timestamp,
          signal: 'SELL',
          price,
          quantity,
          tradeAmount,
          commission,
          netAmount,
          holdingQty: 0,
          avgBuyPrice,
          profitLoss,
          profitLossRate,
          totalAsset: cash,
          macdData: item,
        });
        
        // 매도 후 초기화
        holdingQty = 0;
        avgBuyPrice = 0;
        totalBuyCost = 0;
      }
    }
    
    return simulations;
  }, [data, initialCapital, commissionRate]);

  // 신호별 필터링
  const filteredData = data.filter(item => {
    if (signalFilter === 'ALL') return true;
    if (signalFilter === 'TRADES') return item.signal === 'BUY' || item.signal === 'SELL';
    return item.signal === signalFilter;
  });

  // 매매 신호만 추출 (BUY, SELL)
  const tradingSignals = data.filter(item => item.signal === 'BUY' || item.signal === 'SELL');
  
  // 시뮬레이션 결과에서 해당 날짜의 거래 정보 찾기
  const findSimulation = (row: MacdResult): TradeSimulation | undefined => {
    const dateStr = row.timestamp || row.date;
    return tradeSimulations.find(sim => {
      const simDateStr = sim.timestamp || sim.date;
      return simDateStr === dateStr && sim.signal === row.signal;
    });
  };

  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const getSignalColor = (signal: string) => {
    switch (signal) {
      case 'BUY':
        return 'success';
      case 'SELL':
        return 'error';
      default:
        return 'default';
    }
  };

  const getSignalText = (signal: string) => {
    switch (signal) {
      case 'BUY':
        return '매수';
      case 'SELL':
        return '매도';
      default:
        return '보유';
    }
  };

  // interval에 따라 날짜 포맷 결정
  const formatDate = (row: MacdResult) => {
    try {
      const dateStr = row.timestamp || row.date;
      if (!dateStr) return '-';
      
      const dateObj = dayjs(dateStr);
      
      if (row.timestamp) {
        // 분봉/시간봉 (timestamp 있음)
        if (interval.endsWith('m') || interval.endsWith('h')) {
          return dateObj.format('YYYY-MM-DD HH:mm');
        }
        return dateObj.format('YYYY-MM-DD HH:mm');
      } else {
        // 일봉 이상 (timestamp 없음)
        if (interval === '1M') {
          return dateObj.format('YYYY-MM');
        }
        return dateObj.format('YYYY-MM-DD');
      }
    } catch {
      return row.date || '-';
    }
  };

  // 페이지네이션 적용 (최신 데이터가 위에 오도록 역순)
  const reversedData = [...filteredData].reverse();
  const paginatedData = reversedData.slice(
    page * rowsPerPage,
    page * rowsPerPage + rowsPerPage
  );

  return (
    <Paper sx={{ width: '100%', mb: 2 }}>
      <Box sx={{ p: 2 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2, flexWrap: 'wrap', gap: 1 }}>
          <Typography variant="h6">{title}</Typography>
          
          <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
            <Typography variant="body2" color="text.secondary">
              거래: {tradeSimulations.length}건
            </Typography>
            {tradeSimulations.length > 0 && (
              <>
                <Chip
                  label={`초기: ${(initialCapital / 10000).toLocaleString()}만원`}
                  size="small"
                  variant="outlined"
                  sx={{ fontSize: '0.75rem' }}
                />
                <Chip
                  label={`최종: ${(tradeSimulations[tradeSimulations.length - 1]?.totalAsset / 10000).toLocaleString(undefined, { maximumFractionDigits: 0 })}만원`}
                  size="small"
                  sx={{ 
                    fontSize: '0.75rem',
                    bgcolor: tradeSimulations[tradeSimulations.length - 1]?.totalAsset >= initialCapital 
                      ? 'rgba(34, 197, 94, 0.2)' 
                      : 'rgba(239, 68, 68, 0.2)',
                    color: tradeSimulations[tradeSimulations.length - 1]?.totalAsset >= initialCapital 
                      ? '#22c55e' 
                      : '#ef4444',
                  }}
                />
                <Chip
                  label={`수익률: ${((tradeSimulations[tradeSimulations.length - 1]?.totalAsset / initialCapital - 1) * 100).toFixed(1)}%`}
                  size="small"
                  sx={{ 
                    fontSize: '0.75rem',
                    fontWeight: 600,
                    bgcolor: tradeSimulations[tradeSimulations.length - 1]?.totalAsset >= initialCapital 
                      ? 'rgba(34, 197, 94, 0.3)' 
                      : 'rgba(239, 68, 68, 0.3)',
                    color: tradeSimulations[tradeSimulations.length - 1]?.totalAsset >= initialCapital 
                      ? '#22c55e' 
                      : '#ef4444',
                  }}
                />
              </>
            )}
            
            <FormControl size="small" sx={{ minWidth: 120 }}>
              <InputLabel>신호 필터</InputLabel>
              <Select
                value={signalFilter}
                label="신호 필터"
                onChange={(e) => {
                  setSignalFilter(e.target.value);
                  setPage(0);
                }}
              >
                <MenuItem value="TRADES">거래만</MenuItem>
                <MenuItem value="ALL">전체</MenuItem>
                <MenuItem value="BUY">매수</MenuItem>
                <MenuItem value="SELL">매도</MenuItem>
                <MenuItem value="HOLD">보유</MenuItem>
              </Select>
            </FormControl>
          </Box>
        </Box>

        <TableContainer sx={{ maxHeight: 500 }}>
          <Table size="small" stickyHeader>
            <TableHead>
              <TableRow>
                <TableCell sx={{ minWidth: 100 }}>날짜</TableCell>
                <TableCell align="center" sx={{ minWidth: 60 }}>신호</TableCell>
                <TableCell align="right" sx={{ minWidth: 100 }}>체결가</TableCell>
                <TableCell align="right" sx={{ minWidth: 90 }}>수량</TableCell>
                <TableCell align="right" sx={{ minWidth: 110 }}>거래금액</TableCell>
                <TableCell align="right" sx={{ minWidth: 70 }}>수수료</TableCell>
                <TableCell align="right" sx={{ minWidth: 110 }}>실거래금액</TableCell>
                <TableCell align="right" sx={{ minWidth: 100 }}>손익</TableCell>
                <TableCell align="right" sx={{ minWidth: 70 }}>수익률</TableCell>
                <TableCell align="right" sx={{ minWidth: 110 }}>총자산</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {paginatedData.map((row, index) => {
                const sim = findSimulation(row);
                const isTrade = row.signal === 'BUY' || row.signal === 'SELL';
                
                return (
                  <TableRow
                    key={index}
                    onClick={() => {
                      if (onRowClick && (row.signal === 'BUY' || row.signal === 'SELL')) {
                        onRowClick(row, sim);
                      }
                    }}
                    sx={{ 
                      '&:last-child td, &:last-child th': { border: 0 },
                      backgroundColor: row.signal !== 'HOLD' ? 
                        (row.signal === 'BUY' ? 'rgba(76, 175, 80, 0.1)' : 'rgba(244, 67, 54, 0.1)') : 
                        'inherit',
                      cursor: (row.signal === 'BUY' || row.signal === 'SELL') && onRowClick ? 'pointer' : 'default',
                      '&:hover': {
                        backgroundColor: (row.signal === 'BUY' || row.signal === 'SELL') && onRowClick
                          ? (row.signal === 'BUY' ? 'rgba(76, 175, 80, 0.2)' : 'rgba(244, 67, 54, 0.2)')
                          : undefined,
                      },
                    }}
                  >
                    <TableCell component="th" scope="row" sx={{ fontSize: '0.8rem' }}>
                      {formatDate(row)}
                    </TableCell>
                    <TableCell align="center">
                      <Chip
                        label={getSignalText(row.signal)}
                        color={getSignalColor(row.signal) as any}
                        size="small"
                        variant={row.signal !== 'HOLD' ? 'filled' : 'outlined'}
                        sx={{ fontSize: '0.75rem', height: 24 }}
                      />
                    </TableCell>
                    <TableCell align="right" sx={{ fontSize: '0.8rem' }}>
                      {row.close?.toLocaleString()}원
                    </TableCell>
                    <TableCell align="right" sx={{ fontSize: '0.8rem' }}>
                      {isTrade && sim ? (
                        <Tooltip title={`${sim.quantity.toFixed(8)}`} arrow>
                          <span>{sim.quantity.toFixed(4)}</span>
                        </Tooltip>
                      ) : '-'}
                    </TableCell>
                    <TableCell align="right" sx={{ fontSize: '0.8rem' }}>
                      {isTrade && sim ? (
                        <Typography 
                          variant="body2" 
                          sx={{ 
                            fontSize: '0.8rem',
                            color: row.signal === 'BUY' ? '#ef4444' : '#22c55e',
                            fontWeight: 500,
                          }}
                        >
                          {row.signal === 'BUY' ? '-' : '+'}{sim.tradeAmount.toLocaleString(undefined, { maximumFractionDigits: 0 })}원
                        </Typography>
                      ) : '-'}
                    </TableCell>
                    <TableCell align="right" sx={{ fontSize: '0.75rem', color: 'text.secondary' }}>
                      {isTrade && sim ? (
                        `${sim.commission.toLocaleString(undefined, { maximumFractionDigits: 0 })}원`
                      ) : '-'}
                    </TableCell>
                    <TableCell align="right" sx={{ fontSize: '0.8rem' }}>
                      {isTrade && sim ? (
                        <Typography 
                          variant="body2" 
                          sx={{ 
                            fontSize: '0.8rem',
                            color: row.signal === 'BUY' ? '#ef4444' : '#22c55e',
                            fontWeight: 600,
                          }}
                        >
                          {row.signal === 'BUY' ? '-' : '+'}{sim.netAmount.toLocaleString(undefined, { maximumFractionDigits: 0 })}원
                        </Typography>
                      ) : '-'}
                    </TableCell>
                    <TableCell align="right" sx={{ fontSize: '0.8rem' }}>
                      {row.signal === 'SELL' && sim ? (
                        <Typography 
                          variant="body2" 
                          sx={{ 
                            fontSize: '0.8rem',
                            color: sim.profitLoss >= 0 ? '#22c55e' : '#ef4444',
                            fontWeight: 600,
                          }}
                        >
                          {sim.profitLoss >= 0 ? '+' : ''}{sim.profitLoss.toLocaleString(undefined, { maximumFractionDigits: 0 })}원
                        </Typography>
                      ) : '-'}
                    </TableCell>
                    <TableCell align="right" sx={{ fontSize: '0.8rem' }}>
                      {row.signal === 'SELL' && sim ? (
                        <Chip
                          label={`${sim.profitLossRate >= 0 ? '+' : ''}${sim.profitLossRate.toFixed(1)}%`}
                          size="small"
                          sx={{ 
                            fontSize: '0.7rem',
                            height: 22,
                            bgcolor: sim.profitLossRate >= 0 ? 'rgba(34, 197, 94, 0.2)' : 'rgba(239, 68, 68, 0.2)',
                            color: sim.profitLossRate >= 0 ? '#22c55e' : '#ef4444',
                            fontWeight: 600,
                          }}
                        />
                      ) : '-'}
                    </TableCell>
                    <TableCell align="right" sx={{ fontSize: '0.8rem', fontWeight: 500 }}>
                      {isTrade && sim ? (
                        `${sim.totalAsset.toLocaleString(undefined, { maximumFractionDigits: 0 })}원`
                      ) : '-'}
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>

        <TablePagination
          rowsPerPageOptions={[5, 10, 25, 50]}
          component="div"
          count={filteredData.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
          labelRowsPerPage="페이지당 행 수:"
          labelDisplayedRows={({ from, to, count }) => 
            `${from}-${to} / 총 ${count !== -1 ? count : `${to}개 이상`}`
          }
        />
      </Box>
    </Paper>
  );
};

export default SignalTable;

