import { useMemo } from 'react';
import {
  TrendingUp,
  TrendingDown,
  Target,
  Shield,
  BarChart3,
  AlertCircle,
} from 'lucide-react';
import type { Trade, Portfolio } from '@/types';
import {
  calculateWinRate,
  calculateSharpeRatio,
  calculateMaxDrawdown,
  formatPrice,
  formatPercent,
} from '@/utils/indicators';

interface AdvancedAnalyticsProps {
  portfolio: Portfolio;
  trades: Trade[];
}

export default function AdvancedAnalytics({ portfolio, trades }: AdvancedAnalyticsProps) {
  const analytics = useMemo(() => {
    if (trades.length === 0) {
      return {
        winRate: 0,
        totalTrades: 0,
        winningTrades: 0,
        losingTrades: 0,
        avgWin: 0,
        avgLoss: 0,
        largestWin: 0,
        largestLoss: 0,
        profitFactor: 0,
        sharpeRatio: 0,
        maxDrawdown: 0,
        avgHoldTime: 0,
        riskRewardRatio: 0,
      };
    }

    const completedTrades = trades.filter((t) => t.pnl !== undefined);
    const winningTrades = completedTrades.filter((t) => t.pnl! > 0);
    const losingTrades = completedTrades.filter((t) => t.pnl! <= 0);

    const totalWins = winningTrades.reduce((sum, t) => sum + t.pnl!, 0);
    const totalLosses = Math.abs(losingTrades.reduce((sum, t) => sum + t.pnl!, 0));

    const avgWin = winningTrades.length > 0 ? totalWins / winningTrades.length : 0;
    const avgLoss = losingTrades.length > 0 ? totalLosses / losingTrades.length : 0;

    const largestWin = winningTrades.length > 0 ? Math.max(...winningTrades.map((t) => t.pnl!)) : 0;
    const largestLoss = losingTrades.length > 0 ? Math.min(...losingTrades.map((t) => t.pnl!)) : 0;

    const profitFactor = totalLosses > 0 ? totalWins / totalLosses : totalWins > 0 ? Infinity : 0;

    // Calculate returns for Sharpe ratio
    const returns = completedTrades.map((t) => (t.pnl! / (t.quantity * t.price)) * 100);
    const sharpeRatio = calculateSharpeRatio(returns);

    // Calculate equity curve for max drawdown
    const equity: number[] = [portfolio.initialCapital];
    let currentEquity = portfolio.initialCapital;

    for (const trade of completedTrades) {
      currentEquity += trade.pnl!;
      equity.push(currentEquity);
    }

    const maxDrawdown = calculateMaxDrawdown(equity);

    const riskRewardRatio = avgLoss > 0 ? avgWin / avgLoss : 0;

    return {
      winRate: calculateWinRate(completedTrades),
      totalTrades: completedTrades.length,
      winningTrades: winningTrades.length,
      losingTrades: losingTrades.length,
      avgWin,
      avgLoss,
      largestWin,
      largestLoss,
      profitFactor,
      sharpeRatio,
      maxDrawdown,
      avgHoldTime: 0, // Would need timestamp tracking
      riskRewardRatio,
    };
  }, [trades, portfolio]);

  const getQualityRating = (value: number, type: string): { color: string; text: string } => {
    switch (type) {
      case 'winRate':
        if (value >= 60) return { color: 'text-green-500', text: 'Excellent' };
        if (value >= 50) return { color: 'text-blue-500', text: 'Good' };
        if (value >= 40) return { color: 'text-yellow-500', text: 'Average' };
        return { color: 'text-red-500', text: 'Poor' };

      case 'sharpe':
        if (value >= 2) return { color: 'text-green-500', text: 'Excellent' };
        if (value >= 1) return { color: 'text-blue-500', text: 'Good' };
        if (value >= 0.5) return { color: 'text-yellow-500', text: 'Average' };
        return { color: 'text-red-500', text: 'Poor' };

      case 'profitFactor':
        if (value >= 2) return { color: 'text-green-500', text: 'Excellent' };
        if (value >= 1.5) return { color: 'text-blue-500', text: 'Good' };
        if (value >= 1) return { color: 'text-yellow-500', text: 'Average' };
        return { color: 'text-red-500', text: 'Poor' };

      case 'maxDrawdown':
        if (value <= 10) return { color: 'text-green-500', text: 'Excellent' };
        if (value <= 20) return { color: 'text-blue-500', text: 'Good' };
        if (value <= 30) return { color: 'text-yellow-500', text: 'Average' };
        return { color: 'text-red-500', text: 'High Risk' };

      default:
        return { color: 'text-gray-500', text: 'N/A' };
    }
  };

  if (trades.length === 0) {
    return (
      <div className="card">
        <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
          <BarChart3 className="w-5 h-5" />
          Advanced Analytics
        </h3>
        <p className="text-center text-gray-400 py-8">
          No trades yet. Execute some trades to see detailed analytics.
        </p>
      </div>
    );
  }

  const winRateQuality = getQualityRating(analytics.winRate, 'winRate');
  const sharpeQuality = getQualityRating(analytics.sharpeRatio, 'sharpe');
  const profitFactorQuality = getQualityRating(analytics.profitFactor, 'profitFactor');
  const drawdownQuality = getQualityRating(analytics.maxDrawdown, 'maxDrawdown');

  return (
    <div className="card">
      <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
        <BarChart3 className="w-5 h-5 text-blue-500" />
        Advanced Analytics
      </h3>

      <div className="grid grid-cols-2 gap-4">
        {/* Win Rate */}
        <div className="bg-dark-bg rounded-lg p-4">
          <div className="flex items-center gap-2 mb-1">
            <Target className="w-4 h-4 text-gray-400" />
            <span className="text-sm text-gray-400">Win Rate</span>
          </div>
          <p className="text-2xl font-bold">{analytics.winRate}%</p>
          <p className={`text-xs ${winRateQuality.color}`}>{winRateQuality.text}</p>
          <p className="text-xs text-gray-500 mt-1">
            {analytics.winningTrades}W / {analytics.losingTrades}L
          </p>
        </div>

        {/* Profit Factor */}
        <div className="bg-dark-bg rounded-lg p-4">
          <div className="flex items-center gap-2 mb-1">
            <TrendingUp className="w-4 h-4 text-gray-400" />
            <span className="text-sm text-gray-400">Profit Factor</span>
          </div>
          <p className="text-2xl font-bold">
            {analytics.profitFactor === Infinity
              ? '∞'
              : analytics.profitFactor.toFixed(2)}
          </p>
          <p className={`text-xs ${profitFactorQuality.color}`}>{profitFactorQuality.text}</p>
          <p className="text-xs text-gray-500 mt-1">Wins / Losses ratio</p>
        </div>

        {/* Sharpe Ratio */}
        <div className="bg-dark-bg rounded-lg p-4">
          <div className="flex items-center gap-2 mb-1">
            <Shield className="w-4 h-4 text-gray-400" />
            <span className="text-sm text-gray-400">Sharpe Ratio</span>
          </div>
          <p className="text-2xl font-bold">{analytics.sharpeRatio.toFixed(2)}</p>
          <p className={`text-xs ${sharpeQuality.color}`}>{sharpeQuality.text}</p>
          <p className="text-xs text-gray-500 mt-1">Risk-adjusted returns</p>
        </div>

        {/* Max Drawdown */}
        <div className="bg-dark-bg rounded-lg p-4">
          <div className="flex items-center gap-2 mb-1">
            <TrendingDown className="w-4 h-4 text-gray-400" />
            <span className="text-sm text-gray-400">Max Drawdown</span>
          </div>
          <p className="text-2xl font-bold text-red-500">-{analytics.maxDrawdown}%</p>
          <p className={`text-xs ${drawdownQuality.color}`}>{drawdownQuality.text}</p>
          <p className="text-xs text-gray-500 mt-1">Largest peak-to-trough</p>
        </div>

        {/* Average Win */}
        <div className="bg-dark-bg rounded-lg p-4">
          <div className="flex items-center gap-2 mb-1">
            <TrendingUp className="w-4 h-4 text-green-500" />
            <span className="text-sm text-gray-400">Avg Win</span>
          </div>
          <p className="text-xl font-semibold text-green-500">
            {formatPrice(analytics.avgWin)}
          </p>
          <p className="text-xs text-gray-500 mt-1">
            Largest: {formatPrice(analytics.largestWin)}
          </p>
        </div>

        {/* Average Loss */}
        <div className="bg-dark-bg rounded-lg p-4">
          <div className="flex items-center gap-2 mb-1">
            <TrendingDown className="w-4 h-4 text-red-500" />
            <span className="text-sm text-gray-400">Avg Loss</span>
          </div>
          <p className="text-xl font-semibold text-red-500">
            {formatPrice(analytics.avgLoss)}
          </p>
          <p className="text-xs text-gray-500 mt-1">
            Largest: {formatPrice(Math.abs(analytics.largestLoss))}
          </p>
        </div>

        {/* Risk/Reward Ratio */}
        <div className="bg-dark-bg rounded-lg p-4 col-span-2">
          <div className="flex items-center gap-2 mb-1">
            <AlertCircle className="w-4 h-4 text-gray-400" />
            <span className="text-sm text-gray-400">Risk/Reward Ratio</span>
          </div>
          <p className="text-2xl font-bold">
            1:{analytics.riskRewardRatio.toFixed(2)}
          </p>
          <p className="text-xs text-gray-500 mt-1">
            Average win vs average loss per trade
          </p>
        </div>
      </div>

      {/* Performance Summary */}
      <div className="mt-4 p-4 bg-dark-bg rounded-lg border border-dark-border">
        <h4 className="font-semibold mb-2">Performance Summary</h4>
        <div className="space-y-2 text-sm">
          <div className="flex justify-between">
            <span className="text-gray-400">Total Trades:</span>
            <span className="font-medium">{analytics.totalTrades}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-gray-400">Net P&L:</span>
            <span
              className={`font-semibold ${
                portfolio.totalPnl >= 0 ? 'text-green-500' : 'text-red-500'
              }`}
            >
              {formatPrice(portfolio.totalPnl)} ({formatPercent(portfolio.totalPnlPercent)})
            </span>
          </div>
          <div className="flex justify-between">
            <span className="text-gray-400">Capital Efficiency:</span>
            <span className="font-medium">
              {((portfolio.totalValue / portfolio.initialCapital - 1) * 100).toFixed(2)}%
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}
