/**
 * TradingStatsPanel Component
 * Displays trading performance statistics and metrics
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  ChartBarIcon,
  ArrowTrendingUpIcon,
  ArrowTrendingDownIcon,
  ArrowPathIcon,
  CurrencyDollarIcon,
  ScaleIcon,
  FireIcon,
  ShieldCheckIcon,
} from '@heroicons/react/24/solid';
import { tradingService } from '../../../services/trading.service';
import type { PaperTrade, AccountSummary } from '../../../types/trading.types';

interface TradingStatsPanelProps {
  compact?: boolean;
}

interface CalculatedStats {
  totalTrades: number;
  winningTrades: number;
  losingTrades: number;
  winRate: number;
  totalPnL: number;
  avgWin: number;
  avgLoss: number;
  profitFactor: number;
  largestWin: number;
  largestLoss: number;
  avgHoldTime: string;
  currentStreak: number;
  streakType: 'win' | 'loss' | 'none';
  sharpeRatio: number;
  maxDrawdown: number;
  maxDrawdownPercent: number;
}

export const TradingStatsPanel: React.FC<TradingStatsPanelProps> = ({ compact = false }) => {
  const [trades, setTrades] = useState<PaperTrade[]>([]);
  const [portfolio, setPortfolio] = useState<AccountSummary | null>(null);
  const [stats, setStats] = useState<CalculatedStats | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Calculate statistics from trades
  const calculateStats = useCallback((tradeList: PaperTrade[]): CalculatedStats => {
    if (tradeList.length === 0) {
      return {
        totalTrades: 0,
        winningTrades: 0,
        losingTrades: 0,
        winRate: 0,
        totalPnL: 0,
        avgWin: 0,
        avgLoss: 0,
        profitFactor: 0,
        largestWin: 0,
        largestLoss: 0,
        avgHoldTime: '0h',
        currentStreak: 0,
        streakType: 'none',
        sharpeRatio: 0,
        maxDrawdown: 0,
        maxDrawdownPercent: 0,
      };
    }

    const closedTrades = tradeList.filter((t) => t.realizedPnl !== undefined && t.realizedPnl !== null);
    const winningTrades = closedTrades.filter((t) => (t.realizedPnl || 0) > 0);
    const losingTrades = closedTrades.filter((t) => (t.realizedPnl || 0) < 0);

    const totalPnL = closedTrades.reduce((sum, t) => sum + (t.realizedPnl || 0), 0);
    const totalWins = winningTrades.reduce((sum, t) => sum + (t.realizedPnl || 0), 0);
    const totalLosses = Math.abs(losingTrades.reduce((sum, t) => sum + (t.realizedPnl || 0), 0));

    // Calculate average hold time
    let avgHoldMs = 0;
    const tradesWithTime = closedTrades.filter((t) => t.closedAt && t.openedAt);
    if (tradesWithTime.length > 0) {
      avgHoldMs =
        tradesWithTime.reduce((sum, t) => {
          const open = new Date(t.openedAt!).getTime();
          const close = new Date(t.closedAt!).getTime();
          return sum + (close - open);
        }, 0) / tradesWithTime.length;
    }
    const avgHoldHours = Math.round(avgHoldMs / (1000 * 60 * 60));
    const avgHoldTime = avgHoldHours < 24 ? `${avgHoldHours}h` : `${Math.round(avgHoldHours / 24)}d`;

    // Calculate streak
    let currentStreak = 0;
    let streakType: 'win' | 'loss' | 'none' = 'none';
    const sortedTrades = [...closedTrades].sort(
      (a, b) => new Date(b.closedAt || 0).getTime() - new Date(a.closedAt || 0).getTime()
    );
    if (sortedTrades.length > 0) {
      const firstPnl = sortedTrades[0].realizedPnl || 0;
      streakType = firstPnl > 0 ? 'win' : firstPnl < 0 ? 'loss' : 'none';
      for (const trade of sortedTrades) {
        const pnl = trade.realizedPnl || 0;
        if ((streakType === 'win' && pnl > 0) || (streakType === 'loss' && pnl < 0)) {
          currentStreak++;
        } else {
          break;
        }
      }
    }

    // Calculate Sharpe Ratio (annualized, assuming daily returns)
    let sharpeRatio = 0;
    if (closedTrades.length >= 2) {
      const returns = closedTrades.map((t) => t.realizedPnl || 0);
      const avgReturn = returns.reduce((a, b) => a + b, 0) / returns.length;
      const variance = returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / returns.length;
      const stdDev = Math.sqrt(variance);
      if (stdDev > 0) {
        sharpeRatio = (avgReturn / stdDev) * Math.sqrt(252);
      }
    }

    // Calculate Max Drawdown
    let maxDrawdown = 0;
    let maxDrawdownPercent = 0;
    if (closedTrades.length > 0) {
      const chronologicalTrades = [...closedTrades].sort(
        (a, b) => new Date(a.closedAt || 0).getTime() - new Date(b.closedAt || 0).getTime()
      );
      let cumulativePnl = 0;
      let peak = 0;
      for (const trade of chronologicalTrades) {
        cumulativePnl += trade.realizedPnl || 0;
        if (cumulativePnl > peak) {
          peak = cumulativePnl;
        }
        const drawdown = peak - cumulativePnl;
        if (drawdown > maxDrawdown) {
          maxDrawdown = drawdown;
          maxDrawdownPercent = peak > 0 ? (drawdown / peak) * 100 : 0;
        }
      }
    }

    return {
      totalTrades: closedTrades.length,
      winningTrades: winningTrades.length,
      losingTrades: losingTrades.length,
      winRate: closedTrades.length > 0 ? (winningTrades.length / closedTrades.length) * 100 : 0,
      totalPnL,
      avgWin: winningTrades.length > 0 ? totalWins / winningTrades.length : 0,
      avgLoss: losingTrades.length > 0 ? totalLosses / losingTrades.length : 0,
      profitFactor: totalLosses > 0 ? totalWins / totalLosses : totalWins > 0 ? Infinity : 0,
      largestWin: winningTrades.length > 0 ? Math.max(...winningTrades.map((t) => t.realizedPnl || 0)) : 0,
      largestLoss: losingTrades.length > 0 ? Math.min(...losingTrades.map((t) => t.realizedPnl || 0)) : 0,
      avgHoldTime,
      currentStreak,
      streakType,
      sharpeRatio,
      maxDrawdown,
      maxDrawdownPercent,
    };
  }, []);

  // Fetch data
  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [tradesData, portfolioData] = await Promise.all([
        tradingService.getPaperTrades(100),
        tradingService.getPaperPortfolio(),
      ]);
      setTrades(tradesData);
      setPortfolio(portfolioData);
      setStats(calculateStats(tradesData));
    } catch (err) {
      setError('Failed to fetch trading stats');
      console.error('Stats fetch error:', err);
    } finally {
      setLoading(false);
    }
  }, [calculateStats]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // Format currency
  const formatCurrency = (value: number) => {
    const prefix = value >= 0 ? '+' : '';
    return `${prefix}$${Math.abs(value).toLocaleString(undefined, {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    })}`;
  };

  if (compact) {
    return (
      <div className="card p-3 space-y-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <ChartBarIcon className="w-4 h-4 text-blue-400" />
            <h4 className="text-sm font-medium text-white">Stats</h4>
          </div>
          <button
            onClick={fetchData}
            disabled={loading}
            className="p-1 text-gray-400 hover:text-white rounded"
          >
            <ArrowPathIcon className={`w-3 h-3 ${loading ? 'animate-spin' : ''}`} />
          </button>
        </div>
        {stats && (
          <div className="grid grid-cols-2 gap-2 text-xs">
            <div>
              <span className="text-gray-400">Win Rate</span>
              <p className={`font-bold ${stats.winRate >= 50 ? 'text-green-400' : 'text-red-400'}`}>
                {stats.winRate.toFixed(1)}%
              </p>
            </div>
            <div>
              <span className="text-gray-400">Total P&L</span>
              <p className={`font-bold ${stats.totalPnL >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                {formatCurrency(stats.totalPnL)}
              </p>
            </div>
            <div>
              <span className="text-gray-400">Trades</span>
              <p className="font-bold text-white">{stats.totalTrades}</p>
            </div>
            <div>
              <span className="text-gray-400">Profit Factor</span>
              <p className={`font-bold ${stats.profitFactor >= 1 ? 'text-green-400' : 'text-red-400'}`}>
                {stats.profitFactor === Infinity ? '∞' : stats.profitFactor.toFixed(2)}
              </p>
            </div>
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="card p-4 space-y-4 h-full overflow-y-auto">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <ChartBarIcon className="w-5 h-5 text-blue-400" />
          <h3 className="text-lg font-semibold text-white">Trading Statistics</h3>
        </div>
        <button
          onClick={fetchData}
          disabled={loading}
          className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors disabled:opacity-50"
        >
          <ArrowPathIcon className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
        </button>
      </div>

      {error && (
        <div className="p-3 bg-red-900/20 border border-red-800 rounded-lg text-sm text-red-400">
          {error}
        </div>
      )}

      {/* Portfolio Summary */}
      {portfolio && (
        <div className="grid grid-cols-2 gap-3">
          <div className="p-3 bg-gray-800 rounded-lg">
            <div className="flex items-center gap-2 mb-1">
              <CurrencyDollarIcon className="w-4 h-4 text-green-400" />
              <span className="text-xs text-gray-400">Total Equity</span>
            </div>
            <p className="text-lg font-bold text-white">
              ${portfolio.totalEquity?.toLocaleString(undefined, { minimumFractionDigits: 2 }) || '0.00'}
            </p>
          </div>
          <div className="p-3 bg-gray-800 rounded-lg">
            <div className="flex items-center gap-2 mb-1">
              <ScaleIcon className="w-4 h-4 text-blue-400" />
              <span className="text-xs text-gray-400">Unrealized P&L</span>
            </div>
            <p className={`text-lg font-bold ${(portfolio.unrealizedPnl || 0) >= 0 ? 'text-green-400' : 'text-red-400'}`}>
              ${portfolio.unrealizedPnl?.toLocaleString(undefined, { minimumFractionDigits: 2 }) || '0.00'}
            </p>
          </div>
        </div>
      )}

      {/* Performance Metrics */}
      {stats && (
        <>
          {/* Win/Loss Stats */}
          <div className="space-y-2">
            <h4 className="text-sm font-medium text-gray-400">Performance</h4>
            <div className="grid grid-cols-3 gap-2">
              <div className="text-center p-2 bg-gray-800 rounded">
                <p className="text-xs text-gray-400">Trades</p>
                <p className="text-lg font-bold text-white">{stats.totalTrades}</p>
              </div>
              <div className="text-center p-2 bg-green-900/30 rounded">
                <p className="text-xs text-green-400">Wins</p>
                <p className="text-lg font-bold text-green-400">{stats.winningTrades}</p>
              </div>
              <div className="text-center p-2 bg-red-900/30 rounded">
                <p className="text-xs text-red-400">Losses</p>
                <p className="text-lg font-bold text-red-400">{stats.losingTrades}</p>
              </div>
            </div>
          </div>

          {/* Win Rate Bar */}
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span className="text-gray-400">Win Rate</span>
              <span className={`font-bold ${stats.winRate >= 50 ? 'text-green-400' : 'text-red-400'}`}>
                {stats.winRate.toFixed(1)}%
              </span>
            </div>
            <div className="h-2 bg-gray-700 rounded-full overflow-hidden">
              <div
                className={`h-full transition-all ${stats.winRate >= 50 ? 'bg-green-500' : 'bg-red-500'}`}
                style={{ width: `${Math.min(stats.winRate, 100)}%` }}
              />
            </div>
          </div>

          {/* P&L Stats */}
          <div className="grid grid-cols-2 gap-3">
            <div className="p-3 bg-gray-800 rounded-lg">
              <p className="text-xs text-gray-400 mb-1">Total P&L</p>
              <p className={`text-lg font-bold ${stats.totalPnL >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                {formatCurrency(stats.totalPnL)}
              </p>
            </div>
            <div className="p-3 bg-gray-800 rounded-lg">
              <div className="flex items-center gap-1 mb-1">
                <ShieldCheckIcon className="w-3 h-3 text-blue-400" />
                <p className="text-xs text-gray-400">Profit Factor</p>
              </div>
              <p className={`text-lg font-bold ${stats.profitFactor >= 1 ? 'text-green-400' : 'text-red-400'}`}>
                {stats.profitFactor === Infinity ? '∞' : stats.profitFactor.toFixed(2)}
              </p>
            </div>
          </div>

          {/* Average Win/Loss */}
          <div className="grid grid-cols-2 gap-3">
            <div className="p-3 bg-green-900/20 rounded-lg border border-green-900/50">
              <div className="flex items-center gap-2 mb-1">
                <ArrowTrendingUpIcon className="w-4 h-4 text-green-400" />
                <p className="text-xs text-green-400">Avg Win</p>
              </div>
              <p className="text-sm font-bold text-green-400">{formatCurrency(stats.avgWin)}</p>
              <p className="text-xs text-gray-500 mt-1">
                Best: {formatCurrency(stats.largestWin)}
              </p>
            </div>
            <div className="p-3 bg-red-900/20 rounded-lg border border-red-900/50">
              <div className="flex items-center gap-2 mb-1">
                <ArrowTrendingDownIcon className="w-4 h-4 text-red-400" />
                <p className="text-xs text-red-400">Avg Loss</p>
              </div>
              <p className="text-sm font-bold text-red-400">-${stats.avgLoss.toFixed(2)}</p>
              <p className="text-xs text-gray-500 mt-1">
                Worst: {formatCurrency(stats.largestLoss)}
              </p>
            </div>
          </div>

          {/* Additional Stats */}
          <div className="grid grid-cols-2 gap-3">
            <div className="p-3 bg-gray-800 rounded-lg">
              <p className="text-xs text-gray-400 mb-1">Avg Hold Time</p>
              <p className="text-sm font-bold text-white">{stats.avgHoldTime}</p>
            </div>
            <div className="p-3 bg-gray-800 rounded-lg">
              <div className="flex items-center gap-1 mb-1">
                <FireIcon className={`w-3 h-3 ${stats.streakType === 'win' ? 'text-green-400' : stats.streakType === 'loss' ? 'text-red-400' : 'text-gray-400'}`} />
                <p className="text-xs text-gray-400">Current Streak</p>
              </div>
              <p className={`text-sm font-bold ${stats.streakType === 'win' ? 'text-green-400' : stats.streakType === 'loss' ? 'text-red-400' : 'text-gray-400'}`}>
                {stats.currentStreak} {stats.streakType !== 'none' ? (stats.streakType === 'win' ? 'Wins' : 'Losses') : '-'}
              </p>
            </div>
          </div>

          {/* Advanced Metrics */}
          <div className="space-y-2">
            <h4 className="text-sm font-medium text-gray-400">Advanced Metrics</h4>
            <div className="grid grid-cols-2 gap-3">
              <div className="p-3 bg-gray-800 rounded-lg">
                <p className="text-xs text-gray-400 mb-1">Sharpe Ratio</p>
                <p className={`text-sm font-bold ${stats.sharpeRatio >= 1 ? 'text-green-400' : stats.sharpeRatio >= 0 ? 'text-yellow-400' : 'text-red-400'}`}>
                  {stats.sharpeRatio.toFixed(2)}
                </p>
                <p className="text-xs text-gray-500 mt-0.5">
                  {stats.sharpeRatio >= 2 ? 'Excellent' : stats.sharpeRatio >= 1 ? 'Good' : stats.sharpeRatio >= 0 ? 'Fair' : 'Poor'}
                </p>
              </div>
              <div className="p-3 bg-gray-800 rounded-lg">
                <p className="text-xs text-gray-400 mb-1">Max Drawdown</p>
                <p className="text-sm font-bold text-red-400">
                  -${stats.maxDrawdown.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </p>
                <p className="text-xs text-gray-500 mt-0.5">
                  {stats.maxDrawdownPercent.toFixed(1)}% from peak
                </p>
              </div>
            </div>
          </div>
        </>
      )}

      {/* Empty State */}
      {!loading && stats?.totalTrades === 0 && (
        <div className="text-center py-8 text-gray-500">
          <ChartBarIcon className="w-10 h-10 mx-auto mb-3 opacity-50" />
          <p className="text-sm">No trading history yet</p>
          <p className="text-xs mt-1">Start paper trading to see your statistics</p>
        </div>
      )}
    </div>
  );
};

export default TradingStatsPanel;
