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

/**
 * Slippage Correlation Analysis
 * Analyzes slippage costs and their correlation with:
 * - Market volatility (ATR)
 * - Volume levels
 * - Time of day
 * - Market conditions
 */

export interface VolatilityBucket {
  range: string;
  minVolatility: number;
  maxVolatility: number;
  tradesCount: number;
  avgSlippage: number;
  winRate: number;
  profitability: number; // avg P&L after slippage
  slippageImpact: number; // % of profit lost to slippage
}

export interface SlippageCorrelationProps {
  trades: Array<{
    id: string;
    entry: number;
    exit: number;
    slippage: number; // Cost in dollars
    volatility?: number; // ATR or similar
    volume?: number; // Trade volume
    profitable: boolean;
    pnl: number;
    grossPnL: number; // Before slippage
    timestamp?: string;
  }>;
  onVolatilityRangeSelect?: (range: VolatilityBucket) => void;
}

export default function SlippageCorrelationAnalysis({
  trades,
  onVolatilityRangeSelect,
}: SlippageCorrelationProps) {
  const volatilityAnalysis = useMemo(() => {
    if (trades.length === 0) return [];

    // Define volatility buckets
    const buckets: VolatilityBucket[] = [
      { range: 'Very Low', minVolatility: 0, maxVolatility: 0.5, tradesCount: 0, avgSlippage: 0, winRate: 0, profitability: 0, slippageImpact: 0 },
      { range: 'Low', minVolatility: 0.5, maxVolatility: 1.0, tradesCount: 0, avgSlippage: 0, winRate: 0, profitability: 0, slippageImpact: 0 },
      { range: 'Medium', minVolatility: 1.0, maxVolatility: 1.5, tradesCount: 0, avgSlippage: 0, winRate: 0, profitability: 0, slippageImpact: 0 },
      { range: 'High', minVolatility: 1.5, maxVolatility: 2.5, tradesCount: 0, avgSlippage: 0, winRate: 0, profitability: 0, slippageImpact: 0 },
      { range: 'Very High', minVolatility: 2.5, maxVolatility: 100, tradesCount: 0, avgSlippage: 0, winRate: 0, profitability: 0, slippageImpact: 0 },
    ];

    // Assign trades to buckets
    trades.forEach(trade => {
      const volatility = trade.volatility || 1.0;
      const bucket = buckets.find(b => volatility >= b.minVolatility && volatility < b.maxVolatility);
      
      if (bucket) {
        bucket.tradesCount += 1;
        bucket.avgSlippage += trade.slippage;
        bucket.profitability += trade.pnl;
        if (trade.profitable) bucket.winRate += 1;
        
        // Calculate slippage impact
        const grossPnL = trade.grossPnL || (trade.pnl + trade.slippage);
        bucket.slippageImpact += grossPnL > 0 ? (trade.slippage / grossPnL) * 100 : 0;
      }
    });

    // Finalize calculations
    return buckets
      .filter(b => b.tradesCount > 0)
      .map(bucket => ({
        ...bucket,
        avgSlippage: bucket.avgSlippage / bucket.tradesCount,
        winRate: (bucket.winRate / bucket.tradesCount) * 100,
        profitability: bucket.profitability / bucket.tradesCount,
        slippageImpact: bucket.slippageImpact / bucket.tradesCount,
      }));
  }, [trades]);

  const slippageMetrics = useMemo(() => {
    if (trades.length === 0) {
      return {
        totalTrades: 0,
        avgSlippage: 0,
        totalSlippageCost: 0,
        maxSlippage: 0,
        minSlippage: 0,
        slippageVariance: 0,
        profitBeforeSlippage: 0,
        profitAfterSlippage: 0,
        slippageImpactPercent: 0,
      };
    }

    const totalSlippage = trades.reduce((sum, t) => sum + t.slippage, 0);
    const avgSlippage = totalSlippage / trades.length;
    const slippages = trades.map(t => t.slippage);
    const maxSlippage = Math.max(...slippages);
    const minSlippage = Math.min(...slippages);

    // Calculate variance
    const slippageVariance = slippages.reduce((sum, s) => sum + Math.pow(s - avgSlippage, 2), 0) / slippages.length;

    const profitBeforeSlippage = trades.reduce((sum, t) => sum + (t.grossPnL || (t.pnl + t.slippage)), 0);
    const profitAfterSlippage = trades.reduce((sum, t) => sum + t.pnl, 0);
    const slippageImpactPercent = profitBeforeSlippage > 0 ? (totalSlippage / profitBeforeSlippage) * 100 : 0;

    return {
      totalTrades: trades.length,
      avgSlippage,
      totalSlippageCost: totalSlippage,
      maxSlippage,
      minSlippage,
      slippageVariance: Math.sqrt(slippageVariance),
      profitBeforeSlippage,
      profitAfterSlippage,
      slippageImpactPercent,
    };
  }, [trades]);

  const bestVolatilityBucket = useMemo(() => {
    return volatilityAnalysis.length > 0
      ? volatilityAnalysis.reduce((best, current) =>
          current.profitability > best.profitability ? current : best
        )
      : null;
  }, [volatilityAnalysis]);

  if (trades.length === 0) {
    return (
      <div className="rounded-lg border border-slate-700 bg-slate-900 p-6 text-center">
        <Activity 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">Slippage 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">Slippage & Correlation 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">Total Slippage Cost</p>
            <p className="text-lg font-bold text-red-400">${slippageMetrics.totalSlippageCost.toFixed(2)}</p>
            <p className="text-xs text-slate-600">
              ${slippageMetrics.avgSlippage.toFixed(2)}/trade avg
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Profit Before Slippage</p>
            <p className={`text-lg font-bold ${slippageMetrics.profitBeforeSlippage >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
              ${slippageMetrics.profitBeforeSlippage.toFixed(2)}
            </p>
            <p className="text-xs text-slate-600">
              Gross P&L
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Profit After Slippage</p>
            <p className={`text-lg font-bold ${slippageMetrics.profitAfterSlippage >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
              ${slippageMetrics.profitAfterSlippage.toFixed(2)}
            </p>
            <p className="text-xs text-slate-600">
              Net P&L
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Slippage Impact</p>
            <p className={`text-lg font-bold ${slippageMetrics.slippageImpactPercent <= 5 ? 'text-emerald-400' : slippageMetrics.slippageImpactPercent <= 10 ? 'text-amber-400' : 'text-red-400'}`}>
              {slippageMetrics.slippageImpactPercent.toFixed(1)}%
            </p>
            <p className="text-xs text-slate-600">
              Of gross profit
            </p>
          </div>
        </div>
      </div>

      {/* Volatility Buckets */}
      <div className="px-4 pb-4 space-y-2">
        <p className="text-xs text-slate-500 font-semibold mb-2">Performance by Market Volatility</p>
        
        {volatilityAnalysis.map((bucket) => {
          const isBest = bestVolatilityBucket?.range === bucket.range;
          const profitColor = bucket.profitability >= 0 ? 'text-emerald-400' : 'text-red-400';
          const slippageImpactColor =
            bucket.slippageImpact <= 5 ? 'text-emerald-400' :
            bucket.slippageImpact <= 10 ? 'text-amber-400' :
            'text-red-400';

          return (
            <div
              key={bucket.range}
              onClick={() => onVolatilityRangeSelect?.(bucket)}
              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 ${
                    bucket.profitability >= 0 ? 'bg-emerald-500/20' : 'bg-red-500/20'
                  }`}>
                    {bucket.profitability >= 0 ? (
                      <TrendingUp className="w-4 h-4 text-emerald-400" />
                    ) : (
                      <TrendingDown className="w-4 h-4 text-red-400" />
                    )}
                  </div>
                  
                  <div>
                    <p className="text-sm font-semibold text-slate-200">{bucket.range} Volatility</p>
                    <p className="text-xs text-slate-500">{bucket.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 ${profitColor}`}>
                    {bucket.profitability >= 0 ? '+' : ''}{bucket.profitability.toFixed(2)}
                  </p>
                  <p className="text-xs font-mono text-slate-500">
                    per trade
                  </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 text-emerald-400">{bucket.winRate.toFixed(1)}%</p>
                  <p className="text-slate-600">Profitable</p>
                </div>

                <div className="bg-slate-800/40 rounded px-2 py-1.5">
                  <p className="text-slate-500 mb-0.5">Avg Slippage</p>
                  <p className="font-bold text-red-400">${bucket.avgSlippage.toFixed(2)}</p>
                  <p className="text-slate-600">Per trade</p>
                </div>

                <div className="bg-slate-800/40 rounded px-2 py-1.5">
                  <p className="text-slate-500 mb-0.5">Slippage Impact</p>
                  <p className={`font-bold ${slippageImpactColor}`}>{bucket.slippageImpact.toFixed(1)}%</p>
                  <p className="text-slate-600">Of profit</p>
                </div>

                <div className="bg-slate-800/40 rounded px-2 py-1.5">
                  <p className="text-slate-500 mb-0.5">Profitability</p>
                  <p className={`font-bold ${profitColor}`}>{bucket.profitability.toFixed(2)}</p>
                  <p className="text-slate-600">Net/trade</p>
                </div>
              </div>

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

      {/* Statistics */}
      <div className="px-4 py-3 bg-slate-800/30 border-t border-slate-700 space-y-2 text-xs">
        <div className="grid grid-cols-2 gap-2">
          <div>
            <p className="text-slate-500 mb-1">Slippage Range</p>
            <p className="font-mono text-slate-300">
              ${slippageMetrics.minSlippage.toFixed(2)} - ${slippageMetrics.maxSlippage.toFixed(2)}
            </p>
          </div>
          <div>
            <p className="text-slate-500 mb-1">Slippage Consistency</p>
            <p className="font-mono text-slate-300">
              ±${slippageMetrics.slippageVariance.toFixed(2)} (StdDev)
            </p>
          </div>
        </div>
      </div>

      {/* Recommendation */}
      <div className={`px-4 py-3 border-t border-slate-700 text-xs ${
        slippageMetrics.slippageImpactPercent <= 5
          ? 'bg-emerald-500/10 text-emerald-200'
          : slippageMetrics.slippageImpactPercent <= 10
          ? 'bg-amber-500/10 text-amber-200'
          : 'bg-red-500/10 text-red-200'
      }`}>
        <p className="font-semibold mb-1">
          {slippageMetrics.slippageImpactPercent <= 5 ? '✓' : slippageMetrics.slippageImpactPercent <= 10 ? '⚠' : '✗'} Slippage Analysis:
        </p>
        <p>
          {slippageMetrics.slippageImpactPercent <= 5
            ? `Excellent slippage management (${slippageMetrics.slippageImpactPercent.toFixed(1)}% impact). Continue current execution strategy.`
            : slippageMetrics.slippageImpactPercent <= 10
            ? `Moderate slippage (${slippageMetrics.slippageImpactPercent.toFixed(1)}% impact). Consider using limit orders or trading lower volatility periods.`
            : `High slippage costs (${slippageMetrics.slippageImpactPercent.toFixed(1)}% impact). Trade only in best volatility conditions and focus on larger moves.`
          }
          {bestVolatilityBucket && ` Best results in <span class="font-mono">${bestVolatilityBucket.range}</span> volatility conditions.`}
        </p>
      </div>
    </div>
  );
}
