import { useMemo } from 'react';
import { PieChart, CheckCircle, AlertCircle } from 'lucide-react';

/**
 * Entry Type Analysis
 * Analyzes profitability by entry signal type
 * Shows which signals are most reliable and profitable
 */

export type SignalType = 'RSI_CROSSOVER' | 'MA_CROSSOVER' | 'BB_BREAKOUT' | 'MACD' | 'SUPPORT_BOUNCE' | 'TREND_CONFIRMATION' | 'NEWS_TRIGGERED';

export interface EntryTypeMetrics {
  signalType: SignalType;
  displayName: string;
  tradesCount: number;
  winRate: number; // %
  profitableCount: number;
  lossCount: number;
  avgProfit: number;
  avgLoss: number;
  totalPnL: number;
  profitFactor: number;
  consistency: number; // 0-100, how consistent is this signal
  reliability: number; // 0-100, confidence in this signal
}

export interface EntryTypeAnalysisProps {
  trades: Array<{
    id: string;
    signalType: SignalType;
    entry: number;
    exit: number;
    quantity: number;
    profitable: boolean;
    pnl: number;
    confidence?: number; // 0-100
  }>;
  onSignalTypeSelect?: (signalType: SignalType) => void;
}

const SIGNAL_DISPLAY_NAMES: Record<SignalType, string> = {
  RSI_CROSSOVER: 'RSI Crossover',
  MA_CROSSOVER: 'MA Crossover',
  BB_BREAKOUT: 'Bollinger Breakout',
  MACD: 'MACD Signal',
  SUPPORT_BOUNCE: 'Support Bounce',
  TREND_CONFIRMATION: 'Trend Confirmed',
  NEWS_TRIGGERED: 'News Event',
};

export default function EntryTypeAnalysis({
  trades,
  onSignalTypeSelect,
}: EntryTypeAnalysisProps) {
  const signalMetrics = useMemo(() => {
    if (trades.length === 0) return [];

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

    // Calculate metrics for each signal type
    return Object.entries(grouped).map(([signalType, typesTrades]) => {
      const wins = typesTrades.filter(t => t.profitable);
      const losses = typesTrades.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);
      const winRate = (wins.length / typesTrades.length) * 100;

      // Consistency = how close results are to average (lower variance = higher consistency)
      const pnls = typesTrades.map(t => t.pnl);
      const avgPnL = pnls.reduce((a, b) => a + b, 0) / pnls.length;
      const variance = pnls.reduce((sum, pnl) => sum + Math.pow(pnl - avgPnL, 2), 0) / pnls.length;
      const stdDev = Math.sqrt(variance);
      const consistency = Math.max(0, 100 - (stdDev / (Math.abs(avgPnL) + 1)) * 100);

      // Reliability = average confidence of trades with this signal type
      const avgConfidence = typesTrades.reduce((sum, t) => sum + (t.confidence || 50), 0) / typesTrades.length;

      return {
        signalType: signalType as SignalType,
        displayName: SIGNAL_DISPLAY_NAMES[signalType as SignalType] || signalType,
        tradesCount: typesTrades.length,
        winRate: winRate,
        profitableCount: wins.length,
        lossCount: losses.length,
        avgProfit: avgWin,
        avgLoss: avgLoss,
        totalPnL: typesTrades.reduce((sum, t) => sum + t.pnl, 0),
        profitFactor: profitFactor,
        consistency: consistency,
        reliability: avgConfidence,
      } as EntryTypeMetrics;
    }).sort((a, b) => b.profitFactor - a.profitFactor); // Sort by profit factor
  }, [trades]);

  const bestSignal = useMemo(() => {
    return signalMetrics.length > 0 ? signalMetrics[0] : null;
  }, [signalMetrics]);

  const overallMetrics = useMemo(() => {
    if (signalMetrics.length === 0) {
      return {
        totalTrades: 0,
        avgWinRate: 0,
        avgProfitFactor: 0,
        diversityScore: 0,
      };
    }

    const totalTrades = signalMetrics.reduce((sum, m) => sum + m.tradesCount, 0);
    const totalWins = signalMetrics.reduce((sum, m) => sum + m.profitableCount, 0);
    const avgProfitFactor = signalMetrics.reduce((sum, m) => sum + m.profitFactor, 0) / signalMetrics.length;
    const diversityScore = Math.min(100, (signalMetrics.length / 7) * 100); // Max 7 signal types

    return {
      totalTrades,
      avgWinRate: (totalWins / totalTrades) * 100,
      avgProfitFactor,
      diversityScore,
    };
  }, [signalMetrics]);

  if (trades.length === 0) {
    return (
      <div className="rounded-lg border border-slate-700 bg-slate-900 p-6 text-center">
        <PieChart 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">Entry type analysis 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">Entry Type Analysis</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">Signal Types Used</p>
            <p className="text-lg font-bold text-slate-300">{signalMetrics.length}</p>
            <p className="text-xs text-slate-600">
              {(signalMetrics.length / 7 * 100).toFixed(0)}% utilized
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Avg Win Rate</p>
            <p className={`text-lg font-bold ${overallMetrics.avgWinRate >= 55 ? 'text-emerald-400' : 'text-amber-400'}`}>
              {overallMetrics.avgWinRate.toFixed(1)}%
            </p>
            <p className="text-xs text-slate-600">
              All signals combined
            </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' : 'text-amber-400'}`}>
              {overallMetrics.avgProfitFactor.toFixed(2)}
            </p>
            <p className="text-xs text-slate-600">
              {overallMetrics.avgProfitFactor >= 1.5 ? 'Strong' : 'Moderate'}
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Signal Diversity</p>
            <p className="text-lg font-bold text-slate-300">{overallMetrics.diversityScore.toFixed(0)}%</p>
            <p className="text-xs text-slate-600">
              {signalMetrics.length} of 7 types
            </p>
          </div>
        </div>
      </div>

      {/* Signal Types List */}
      <div className="px-4 pb-4 space-y-2">
        {signalMetrics.map((signal) => {
          const isBest = bestSignal?.signalType === signal.signalType;
          const winRateColor =
            signal.winRate >= 60 ? 'text-emerald-400' :
            signal.winRate >= 50 ? 'text-amber-400' :
            'text-red-400';
          
          const profitFactorColor =
            signal.profitFactor >= 2 ? 'text-emerald-400' :
            signal.profitFactor >= 1.5 ? 'text-amber-400' :
            signal.profitFactor >= 1 ? 'text-blue-400' :
            'text-red-400';

          const consistencyColor =
            signal.consistency >= 70 ? 'text-emerald-400' :
            signal.consistency >= 50 ? 'text-amber-400' :
            'text-red-400';

          return (
            <div
              key={signal.signalType}
              onClick={() => onSignalTypeSelect?.(signal.signalType)}
              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 ${
                    signal.profitFactor >= 1.5 ? 'bg-emerald-500/20' : 'bg-slate-700/30'
                  }`}>
                    {signal.totalPnL >= 0 ? (
                      <CheckCircle className={`w-4 h-4 ${isBest ? 'text-emerald-400' : 'text-slate-400'}`} />
                    ) : (
                      <AlertCircle className="w-4 h-4 text-red-400" />
                    )}
                  </div>
                  
                  <div>
                    <p className="text-sm font-semibold text-slate-200">{signal.displayName}</p>
                    <p className="text-xs text-slate-500">{signal.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 Signal
                    </span>
                  )}
                </div>

                <div className="text-right">
                  <p className={`text-sm font-bold font-mono ${
                    signal.totalPnL >= 0 ? 'text-emerald-400' : 'text-red-400'
                  }`}>
                    {signal.totalPnL >= 0 ? '+' : ''}{signal.totalPnL.toFixed(2)}
                  </p>
                  <p className={`text-xs font-mono ${winRateColor}`}>
                    {signal.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}`}>{signal.winRate.toFixed(1)}%</p>
                  <p className="text-slate-600">{signal.profitableCount}W {signal.lossCount}L</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}`}>{signal.profitFactor.toFixed(2)}</p>
                  <p className="text-slate-600">Win/Loss ratio</p>
                </div>

                <div className="bg-slate-800/40 rounded px-2 py-1.5">
                  <p className="text-slate-500 mb-0.5">Consistency</p>
                  <p className={`font-bold ${consistencyColor}`}>{signal.consistency.toFixed(0)}%</p>
                  <p className="text-slate-600">Result spread</p>
                </div>

                <div className="bg-slate-800/40 rounded px-2 py-1.5">
                  <p className="text-slate-500 mb-0.5">Reliability</p>
                  <p className="font-bold text-blue-400">{signal.reliability.toFixed(0)}%</p>
                  <p className="text-slate-600">Confidence avg</p>
                </div>
              </div>

              {/* Metrics Comparison */}
              <div className="mt-2 space-y-1">
                <div className="text-xs">
                  <div className="flex justify-between mb-0.5">
                    <span className="text-slate-500">Win Rate</span>
                    <span className="text-slate-400">{signal.winRate.toFixed(1)}%</span>
                  </div>
                  <div className="h-1 bg-slate-700/50 rounded-full overflow-hidden">
                    <div
                      className={`h-full rounded-full transition-all ${winRateColor}`}
                      style={{ width: `${Math.min(signal.winRate, 100)}%` }}
                    />
                  </div>
                </div>

                <div className="text-xs">
                  <div className="flex justify-between mb-0.5">
                    <span className="text-slate-500">Consistency</span>
                    <span className="text-slate-400">{signal.consistency.toFixed(0)}%</span>
                  </div>
                  <div className="h-1 bg-slate-700/50 rounded-full overflow-hidden">
                    <div
                      className={`h-full rounded-full transition-all ${consistencyColor}`}
                      style={{ width: `${Math.min(signal.consistency, 100)}%` }}
                    />
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Footer: Recommendation */}
      {bestSignal && (
        <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>
            <span className="font-mono font-bold">{bestSignal.displayName}</span> is your most reliable signal 
            ({bestSignal.winRate.toFixed(1)}% win rate, {bestSignal.profitFactor.toFixed(2)} profit factor). 
            Prioritize these trades with {bestSignal.reliability.toFixed(0)}% confidence.
          </p>
        </div>
      )}
    </div>
  );
}
