import { useMemo } from 'react';
import { BarChart3, TrendingUp, TrendingDown } from 'lucide-react';

/**
 * Performance by Timeframe Analysis
 * Analyzes which timeframes are most profitable for your trading
 * Helps optimize strategy by identifying best trading windows
 */

export interface TimeframeMetrics {
  timeframe: string;
  tradesCount: number;
  winRate: number; // %
  avgProfit: number;
  avgLoss: number;
  profitFactor: number; // avg win / avg loss
  totalPnL: number;
  profitableTradesCount: number;
  looseTrades: number;
  bestTrade: number;
  worstTrade: number;
}

export interface PerformanceByTimeframeProps {
  trades: Array<{
    id: string;
    timeframe: string;
    entry: number;
    exit: number;
    quantity: number;
    profitable: boolean;
    pnl: number;
  }>;
  onTimeframeSelect?: (timeframe: string) => void;
}

export default function PerformanceByTimeframe({
  trades,
  onTimeframeSelect,
}: PerformanceByTimeframeProps) {
  const timeframeMetrics = useMemo(() => {
    if (trades.length === 0) return [];

    // Group by timeframe
    const grouped = trades.reduce((acc, trade) => {
      if (!acc[trade.timeframe]) {
        acc[trade.timeframe] = [];
      }
      acc[trade.timeframe].push(trade);
      return acc;
    }, {} as Record<string, typeof trades>);

    // Calculate metrics for each timeframe
    return Object.entries(grouped).map(([tf, tfTrades]) => {
      const wins = tfTrades.filter(t => t.profitable);
      const losses = tfTrades.filter(t => !t.profitable);
      
      const winPnLs = wins.map(t => t.pnl);
      const lossPnLs = losses.map(t => t.pnl);
      
      const avgWin = winPnLs.length > 0 ? winPnLs.reduce((a, b) => a + b, 0) / winPnLs.length : 0;
      const avgLoss = lossPnLs.length > 0 ? Math.abs(lossPnLs.reduce((a, b) => a + b, 0) / lossPnLs.length) : 0;
      
      const profitFactor = avgLoss > 0 ? avgWin / avgLoss : (avgWin > 0 ? Infinity : 0);

      return {
        timeframe: tf,
        tradesCount: tfTrades.length,
        winRate: (wins.length / tfTrades.length) * 100,
        avgProfit: avgWin,
        avgLoss: avgLoss,
        profitFactor: profitFactor,
        totalPnL: tfTrades.reduce((sum, t) => sum + t.pnl, 0),
        profitableTradesCount: wins.length,
        looseTrades: losses.length,
        bestTrade: Math.max(...tfTrades.map(t => t.pnl)),
        worstTrade: Math.min(...tfTrades.map(t => t.pnl)),
      } as TimeframeMetrics;
    }).sort((a, b) => b.tradesCount - a.tradesCount); // Sort by trade count
  }, [trades]);

  // Find best and worst timeframes
  const bestTimeframe = useMemo(() => {
    return timeframeMetrics.length > 0
      ? timeframeMetrics.reduce((best, current) =>
          current.profitFactor > best.profitFactor ? current : best
        )
      : null;
  }, [timeframeMetrics]);

  const overallMetrics = useMemo(() => {
    if (timeframeMetrics.length === 0) {
      return {
        totalTrades: 0,
        overallWinRate: 0,
        overallPnL: 0,
        avgProfitFactor: 0,
      };
    }

    const totalTrades = timeframeMetrics.reduce((sum, m) => sum + m.tradesCount, 0);
    const totalWins = timeframeMetrics.reduce((sum, m) => sum + m.profitableTradesCount, 0);
    const totalPnL = timeframeMetrics.reduce((sum, m) => sum + m.totalPnL, 0);
    const avgProfitFactor = timeframeMetrics.reduce((sum, m) => sum + m.profitFactor, 0) / timeframeMetrics.length;

    return {
      totalTrades,
      overallWinRate: (totalWins / totalTrades) * 100,
      overallPnL: totalPnL,
      avgProfitFactor,
    };
  }, [timeframeMetrics]);

  if (trades.length === 0) {
    return (
      <div className="rounded-lg border border-slate-700 bg-slate-900 p-6 text-center">
        <BarChart3 className="w-8 h-8 text-slate-600 mx-auto mb-2" />
        <p className="text-slate-400">No trading data available</p>
        <p className="text-xs text-slate-600 mt-1">Trade history will appear here</p>
      </div>
    );
  }

  return (
    <div className="rounded-lg border border-slate-700 bg-slate-900 space-y-4 overflow-hidden">
      {/* Header Summary */}
      <div className="bg-slate-800/50 p-4 border-b border-slate-700">
        <h3 className="font-semibold text-slate-200 mb-3">Performance by Timeframe</h3>
        
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Total Trades</p>
            <p className="text-lg font-bold text-slate-300">{overallMetrics.totalTrades}</p>
            <p className="text-xs text-slate-600">
              {timeframeMetrics.length} timeframes
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Overall Win Rate</p>
            <p className={`text-lg font-bold ${overallMetrics.overallWinRate >= 60 ? 'text-emerald-400' : overallMetrics.overallWinRate >= 50 ? 'text-amber-400' : 'text-red-400'}`}>
              {overallMetrics.overallWinRate.toFixed(1)}%
            </p>
            <p className="text-xs text-slate-600">
              {Math.round(overallMetrics.overallWinRate / 10)} / 10
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Total P&L</p>
            <p className={`text-lg font-bold ${overallMetrics.overallPnL >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
              ${Math.abs(overallMetrics.overallPnL).toFixed(2)}
            </p>
            <p className="text-xs text-slate-600">
              {overallMetrics.overallPnL >= 0 ? '+' : '-'}{((overallMetrics.overallPnL / overallMetrics.totalTrades) || 0).toFixed(2)}/trade
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Avg Profit Factor</p>
            <p className={`text-lg font-bold ${overallMetrics.avgProfitFactor >= 1.5 ? 'text-emerald-400' : overallMetrics.avgProfitFactor >= 1 ? 'text-amber-400' : 'text-red-400'}`}>
              {overallMetrics.avgProfitFactor.toFixed(2)}
            </p>
            <p className="text-xs text-slate-600">
              {overallMetrics.avgProfitFactor >= 1.5 ? 'Excellent' : overallMetrics.avgProfitFactor >= 1 ? 'Good' : 'Poor'}
            </p>
          </div>
        </div>
      </div>

      {/* Timeframe List */}
      <div className="px-4 pb-4 space-y-2">
        {timeframeMetrics.map((tf) => {
          const isBest = bestTimeframe?.timeframe === tf.timeframe;
          const winRateColor =
            tf.winRate >= 65 ? 'text-emerald-400' :
            tf.winRate >= 55 ? 'text-amber-400' :
            'text-red-400';
          
          const profitFactorColor =
            tf.profitFactor >= 2 ? 'text-emerald-400' :
            tf.profitFactor >= 1.5 ? 'text-amber-400' :
            tf.profitFactor >= 1 ? 'text-blue-400' :
            'text-red-400';

          return (
            <div
              key={tf.timeframe}
              onClick={() => onTimeframeSelect?.(tf.timeframe)}
              className={`p-3 rounded-lg border transition-all cursor-pointer ${
                isBest
                  ? 'border-emerald-500/40 bg-emerald-500/5 hover:bg-emerald-500/10'
                  : 'border-slate-700 bg-slate-800/30 hover:bg-slate-800/50'
              }`}
            >
              {/* Header */}
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-3">
                  <div className={`p-2 rounded-lg ${
                    tf.profitFactor >= 1.5 ? 'bg-emerald-500/20' : 'bg-slate-700/30'
                  }`}>
                    {tf.totalPnL >= 0 ? (
                      <TrendingUp className={`w-4 h-4 ${isBest ? 'text-emerald-400' : 'text-slate-400'}`} />
                    ) : (
                      <TrendingDown className="w-4 h-4 text-red-400" />
                    )}
                  </div>
                  
                  <div>
                    <p className="text-sm font-semibold text-slate-200">{tf.timeframe}</p>
                    <p className="text-xs text-slate-500">{tf.tradesCount} trades</p>
                  </div>

                  {isBest && (
                    <span className="ml-auto mr-2 text-xs bg-emerald-500/20 text-emerald-300 px-2 py-1 rounded font-semibold">
                      ⭐ Best
                    </span>
                  )}
                </div>

                <div className="text-right">
                  <p className={`text-sm font-bold font-mono ${
                    tf.totalPnL >= 0 ? 'text-emerald-400' : 'text-red-400'
                  }`}>
                    {tf.totalPnL >= 0 ? '+' : ''}{tf.totalPnL.toFixed(2)}
                  </p>
                  <p className={`text-xs font-mono ${winRateColor}`}>
                    {tf.winRate.toFixed(1)}%
                  </p>
                </div>
              </div>

              {/* Metrics Grid */}
              <div className="grid grid-cols-4 gap-2 text-xs">
                <div className="bg-slate-800/40 rounded px-2 py-1.5">
                  <p className="text-slate-500 mb-0.5">Win Rate</p>
                  <p className={`font-bold ${winRateColor}`}>{tf.winRate.toFixed(1)}%</p>
                  <p className="text-slate-600">{tf.profitableTradesCount}W {tf.looseTrades}L</p>
                </div>

                <div className="bg-slate-800/40 rounded px-2 py-1.5">
                  <p className="text-slate-500 mb-0.5">Avg Win</p>
                  <p className="font-bold text-emerald-400">${tf.avgProfit.toFixed(2)}</p>
                  <p className="text-slate-600">Best: ${tf.bestTrade.toFixed(2)}</p>
                </div>

                <div className="bg-slate-800/40 rounded px-2 py-1.5">
                  <p className="text-slate-500 mb-0.5">Avg Loss</p>
                  <p className="font-bold text-red-400">${tf.avgLoss.toFixed(2)}</p>
                  <p className="text-slate-600">Worst: ${tf.worstTrade.toFixed(2)}</p>
                </div>

                <div className="bg-slate-800/40 rounded px-2 py-1.5">
                  <p className="text-slate-500 mb-0.5">Profit Factor</p>
                  <p className={`font-bold ${profitFactorColor}`}>{tf.profitFactor.toFixed(2)}</p>
                  <p className="text-slate-600">
                    {tf.profitFactor >= 2 ? '⭐ Excellent' : tf.profitFactor >= 1.5 ? '✓ Good' : '↗ Poor'}
                  </p>
                </div>
              </div>

              {/* Win Rate Bar */}
              <div className="mt-2">
                <div className="h-1.5 bg-slate-700/50 rounded-full overflow-hidden">
                  <div
                    className={`h-full rounded-full transition-all ${
                      tf.winRate >= 65 ? 'bg-emerald-500' :
                      tf.winRate >= 55 ? 'bg-amber-500' :
                      'bg-red-500'
                    }`}
                    style={{ width: `${Math.min(tf.winRate, 100)}%` }}
                  />
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Footer: Recommendation */}
      {bestTimeframe && (
        <div className="px-4 py-3 bg-emerald-500/10 border-t border-slate-700 text-xs text-emerald-200">
          <p className="font-semibold mb-1">💡 Recommendation:</p>
          <p>
            Focus more trades on <span className="font-mono font-bold">{bestTimeframe.timeframe}</span> timeframe - 
            it shows the best profit factor ({bestTimeframe.profitFactor.toFixed(2)}) with {bestTimeframe.winRate.toFixed(1)}% win rate.
          </p>
        </div>
      )}
    </div>
  );
}
