import type { BacktestResult } from '../types/backtest.types';
import { DataTable } from '@/components/ui/DataTable';
import type { ColumnDef } from '@tanstack/react-table';

interface BacktestTradesProps {
  result: any | null;
  isLoading: boolean;
}

export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
  if (isLoading) {
    return (
      <div className="bg-surface-secondary rounded-lg border border-border p-4 animate-pulse">
        <div className="space-y-3">
          {[...Array(5)].map((_, i) => (
            <div key={i} className="h-16 bg-surface rounded"></div>
          ))}
        </div>
      </div>
    );
  }

  if (!result || !result.trades || result.trades.length === 0) {
    return (
      <div className="bg-surface-secondary rounded-lg border border-border p-8 text-center">
        <p className="text-text-secondary">No trades executed in this backtest.</p>
      </div>
    );
  }

  // Add debug logging
  console.log('Trades data:', result.trades);
  
  const columns: ColumnDef<any>[] = [
    {
      accessorKey: 'symbol',
      header: 'Symbol',
      size: 100,
      cell: ({ getValue }) => (
        <span className="text-sm font-medium text-text-primary">{getValue() as string}</span>
      ),
    },
    {
      id: 'side',
      header: 'Side',
      size: 80,
      cell: ({ row }) => {
        const trade = row.original;
        const side = trade.side || (trade.quantity > 0 ? 'buy' : 'sell');
        return (
          <span className={`inline-flex px-2 py-1 text-xs font-medium rounded-md ${
            side === 'buy' 
              ? 'bg-success/10 text-success' 
              : 'bg-error/10 text-error'
          }`}>
            {side.toUpperCase()}
          </span>
        );
      },
    },
    {
      id: 'date',
      header: 'Date',
      size: 180,
      cell: ({ row }) => {
        const trade = row.original;
        const date = trade.timestamp || trade.entryDate || trade.date;
        return (
          <span className="text-sm text-text-secondary">
            {date ? new Date(date).toLocaleString() : '-'}
          </span>
        );
      },
    },
    {
      id: 'price',
      header: 'Price',
      size: 100,
      cell: ({ row }) => {
        const trade = row.original;
        const price = trade.price || trade.entryPrice;
        return (
          <span className="text-sm text-text-primary">
            ${price != null ? price.toFixed(2) : '0.00'}
          </span>
        );
      },
    },
    {
      accessorKey: 'quantity',
      header: 'Quantity',
      size: 80,
      cell: ({ getValue }) => {
        const qty = Math.abs(getValue() as number || 0);
        return <span className="text-sm text-text-primary">{qty}</span>;
      },
    },
    {
      accessorKey: 'commission',
      header: 'Commission',
      size: 100,
      cell: ({ getValue }) => {
        const commission = getValue() as number || 0;
        return (
          <span className="text-sm text-text-secondary">
            ${commission.toFixed(2)}
          </span>
        );
      },
    },
    {
      id: 'pnl',
      header: 'P&L',
      size: 100,
      cell: ({ row }) => {
        const trade = row.original;
        const pnl = trade.pnl || trade.realizedPnl || 0;
        return (
          <span className={`text-sm font-medium ${
            pnl >= 0 ? 'text-success' : 'text-error'
          }`}>
            ${pnl.toFixed(2)}
          </span>
        );
      },
    },
  ];

  // Calculate trade statistics
  const tradeStats = result.trades.reduce((stats: any, trade: any) => {
    const pnl = trade.pnl || trade.realizedPnl || 0;
    if (pnl > 0) {
      stats.wins++;
      stats.totalWin += pnl;
    } else if (pnl < 0) {
      stats.losses++;
      stats.totalLoss += Math.abs(pnl);
    }
    stats.totalPnL += pnl;
    return stats;
  }, { wins: 0, losses: 0, totalWin: 0, totalLoss: 0, totalPnL: 0 });
  
  const winRate = result.trades.length > 0 ? (tradeStats.wins / result.trades.length) * 100 : 0;
  
  return (
    <div>
      <div className="mb-4 grid grid-cols-1 md:grid-cols-5 gap-4">
        <div className="bg-surface-secondary rounded-lg border border-border p-3">
          <p className="text-xs text-text-secondary">Total Trades</p>
          <p className="text-lg font-medium text-text-primary">{result.trades.length}</p>
        </div>
        <div className="bg-surface-secondary rounded-lg border border-border p-3">
          <p className="text-xs text-text-secondary">Win Rate</p>
          <p className="text-lg font-medium text-text-primary">{winRate.toFixed(1)}%</p>
        </div>
        <div className="bg-surface-secondary rounded-lg border border-border p-3">
          <p className="text-xs text-text-secondary">Wins</p>
          <p className="text-lg font-medium text-success">{tradeStats.wins}</p>
        </div>
        <div className="bg-surface-secondary rounded-lg border border-border p-3">
          <p className="text-xs text-text-secondary">Losses</p>
          <p className="text-lg font-medium text-error">{tradeStats.losses}</p>
        </div>
        <div className="bg-surface-secondary rounded-lg border border-border p-3">
          <p className="text-xs text-text-secondary">Total P&L</p>
          <p className={`text-lg font-medium ${tradeStats.totalPnL >= 0 ? 'text-success' : 'text-error'}`}>
            ${tradeStats.totalPnL.toFixed(2)}
          </p>
        </div>
      </div>
      
      <DataTable
        data={result.trades}
        columns={columns}
        className="bg-surface-secondary rounded-lg border border-border"
        height={400}
      />
      
      {result.positions && Object.keys(result.positions).length > 0 && (() => {
        const positionsArray = Object.entries(result.positions).map(([symbol, position]) => ({
          symbol,
          ...position
        }));
        
        const positionColumns: ColumnDef<typeof positionsArray[0]>[] = [
          {
            accessorKey: 'symbol',
            header: 'Symbol',
            size: 100,
            cell: ({ getValue }) => (
              <span className="text-sm font-medium text-text-primary">{getValue() as string}</span>
            ),
          },
          {
            accessorKey: 'quantity',
            header: 'Quantity',
            size: 100,
            cell: ({ getValue }) => (
              <span className="text-sm text-text-primary">{getValue() as number || 0}</span>
            ),
          },
          {
            accessorKey: 'averagePrice',
            header: 'Avg Price',
            size: 120,
            cell: ({ getValue }) => {
              const price = getValue() as number;
              return (
                <span className="text-sm text-text-primary">
                  ${price != null ? price.toFixed(2) : '0.00'}
                </span>
              );
            },
          },
          {
            accessorKey: 'unrealizedPnl',
            header: 'Unrealized P&L',
            size: 150,
            cell: ({ getValue }) => {
              const pnl = getValue() as number || 0;
              return (
                <span className={`text-sm font-medium ${
                  pnl >= 0 ? 'text-success' : 'text-error'
                }`}>
                  ${pnl != null ? pnl.toFixed(2) : '0.00'}
                </span>
              );
            },
          },
        ];
        
        return (
          <div className="mt-6">
            <h4 className="text-base font-medium text-text-primary mb-3">Open Positions</h4>
            <DataTable
              data={positionsArray}
              columns={positionColumns}
              className="bg-surface-secondary rounded-lg border border-border"
              height={200}
            />
          </div>
        );
      })()}
    </div>
  );
}