/**
 * BacktestResultsVisualization Component
 * Comprehensive backtest results viewer
 * OQI-006: Senales ML
 */

import React, { useState, useMemo } from 'react';
import {
  LineChart,
  TrendingUp,
  TrendingDown,
  Target,
  BarChart3,
  Activity,
  AlertTriangle,
  DollarSign,
  Percent,
  Calendar,
  Clock,
  ChevronDown,
  ChevronUp,
  Download,
  Zap,
  Shield,
  Award,
} from 'lucide-react';

export interface BacktestTrade {
  id: string;
  symbol: string;
  direction: 'BUY' | 'SELL';
  entryPrice: number;
  exitPrice: number;
  entryTime: string;
  exitTime: string;
  profit: number;
  profitPercent: number;
  duration: number; // minutes
}

export interface BacktestResult {
  strategyName: string;
  period: { start: string; end: string };
  initialCapital: number;
  finalCapital: number;
  totalReturn: number;
  totalReturnPercent: number;
  totalTrades: number;
  winningTrades: number;
  losingTrades: number;
  winRate: number;
  profitFactor: number;
  sharpeRatio: number;
  sortinoRatio?: number;
  maxDrawdown: number;
  maxDrawdownPercent: number;
  avgWin: number;
  avgLoss: number;
  avgRR: number;
  expectancy: number;
  avgTradeDuration: number;
  largestWin: number;
  largestLoss: number;
  longestWinStreak: number;
  longestLoseStreak: number;
  trades: BacktestTrade[];
  equityCurve?: { date: string; equity: number; drawdown: number }[];
  monthlyReturns?: Record<string, number>;
}

interface BacktestResultsVisualizationProps {
  result: BacktestResult;
  onExport?: (format: 'csv' | 'pdf') => void;
  onTradeSelect?: (trade: BacktestTrade) => void;
  compact?: boolean;
}

const BacktestResultsVisualization: React.FC<BacktestResultsVisualizationProps> = ({
  result,
  onExport,
  onTradeSelect,
  compact = false,
}) => {
  const [activeTab, setActiveTab] = useState<'overview' | 'trades' | 'monthly'>('overview');
  const [showAllTrades, setShowAllTrades] = useState(false);
  const [expandedTradeId, setExpandedTradeId] = useState<string | null>(null);

  const isProfitable = result.totalReturn >= 0;
  const isGoodPerformance = result.winRate >= 50 && result.profitFactor >= 1.5;

  const getMetricColor = (value: number, thresholds: { good: number; bad: number }, inverse = false) => {
    if (inverse) {
      if (value <= thresholds.good) return 'text-green-400';
      if (value >= thresholds.bad) return 'text-red-400';
      return 'text-yellow-400';
    }
    if (value >= thresholds.good) return 'text-green-400';
    if (value <= thresholds.bad) return 'text-red-400';
    return 'text-yellow-400';
  };

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value);
  };

  const formatPercent = (value: number) => {
    return `${value >= 0 ? '+' : ''}${value.toFixed(2)}%`;
  };

  const formatDuration = (minutes: number) => {
    if (minutes < 60) return `${minutes}m`;
    if (minutes < 1440) return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
    return `${Math.floor(minutes / 1440)}d`;
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
    });
  };

  const displayedTrades = useMemo(() => {
    return showAllTrades ? result.trades : result.trades.slice(0, 10);
  }, [result.trades, showAllTrades]);

  return (
    <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-lg ${isProfitable ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
            <LineChart className={`w-5 h-5 ${isProfitable ? 'text-green-400' : 'text-red-400'}`} />
          </div>
          <div>
            <h3 className="font-semibold text-white">{result.strategyName}</h3>
            <p className="text-xs text-gray-500">
              {formatDate(result.period.start)} - {formatDate(result.period.end)}
            </p>
          </div>
        </div>

        {onExport && (
          <div className="flex items-center gap-2">
            <button
              onClick={() => onExport('csv')}
              className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-white rounded text-xs"
            >
              Export CSV
            </button>
            <button
              onClick={() => onExport('pdf')}
              className="px-3 py-1.5 bg-blue-600 hover:bg-blue-500 text-white rounded text-xs"
            >
              Export PDF
            </button>
          </div>
        )}
      </div>

      {/* Main Result Card */}
      <div className={`p-6 rounded-xl mb-6 ${
        isProfitable
          ? 'bg-gradient-to-r from-green-500/10 to-emerald-500/10 border border-green-500/30'
          : 'bg-gradient-to-r from-red-500/10 to-rose-500/10 border border-red-500/30'
      }`}>
        <div className="flex items-center justify-between">
          <div>
            <div className="text-gray-400 text-sm mb-1">Total Return</div>
            <div className={`text-4xl font-bold ${isProfitable ? 'text-green-400' : 'text-red-400'}`}>
              {formatCurrency(result.totalReturn)}
            </div>
            <div className={`text-lg ${isProfitable ? 'text-green-400' : 'text-red-400'}`}>
              {formatPercent(result.totalReturnPercent)}
            </div>
          </div>
          <div className="text-right">
            <div className="flex items-center gap-2 mb-2">
              {isGoodPerformance ? (
                <Award className="w-6 h-6 text-yellow-400" />
              ) : (
                <AlertTriangle className="w-6 h-6 text-yellow-400" />
              )}
              <span className="text-gray-400 text-sm">
                {isGoodPerformance ? 'Strong Performance' : 'Needs Optimization'}
              </span>
            </div>
            <div className="text-xs text-gray-500">
              {formatCurrency(result.initialCapital)} → {formatCurrency(result.finalCapital)}
            </div>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-2 mb-4">
        {(['overview', 'trades', 'monthly'] as const).map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`px-4 py-2 rounded text-sm font-medium transition-colors ${
              activeTab === tab
                ? 'bg-blue-600 text-white'
                : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
            }`}
          >
            {tab.charAt(0).toUpperCase() + tab.slice(1)}
          </button>
        ))}
      </div>

      {/* Overview Tab */}
      {activeTab === 'overview' && (
        <div className="space-y-4">
          {/* Key Metrics Grid */}
          <div className="grid grid-cols-4 gap-3">
            <div className="p-3 bg-gray-900/50 rounded-lg">
              <div className="flex items-center gap-2 mb-1">
                <Target className="w-4 h-4 text-blue-400" />
                <span className="text-xs text-gray-400">Win Rate</span>
              </div>
              <div className={`text-xl font-bold ${getMetricColor(result.winRate, { good: 55, bad: 40 })}`}>
                {result.winRate.toFixed(1)}%
              </div>
            </div>
            <div className="p-3 bg-gray-900/50 rounded-lg">
              <div className="flex items-center gap-2 mb-1">
                <Zap className="w-4 h-4 text-yellow-400" />
                <span className="text-xs text-gray-400">Profit Factor</span>
              </div>
              <div className={`text-xl font-bold ${getMetricColor(result.profitFactor, { good: 1.5, bad: 1 })}`}>
                {result.profitFactor.toFixed(2)}
              </div>
            </div>
            <div className="p-3 bg-gray-900/50 rounded-lg">
              <div className="flex items-center gap-2 mb-1">
                <Activity className="w-4 h-4 text-purple-400" />
                <span className="text-xs text-gray-400">Sharpe Ratio</span>
              </div>
              <div className={`text-xl font-bold ${getMetricColor(result.sharpeRatio, { good: 1.5, bad: 0.5 })}`}>
                {result.sharpeRatio.toFixed(2)}
              </div>
            </div>
            <div className="p-3 bg-gray-900/50 rounded-lg">
              <div className="flex items-center gap-2 mb-1">
                <Shield className="w-4 h-4 text-red-400" />
                <span className="text-xs text-gray-400">Max Drawdown</span>
              </div>
              <div className={`text-xl font-bold ${getMetricColor(result.maxDrawdownPercent, { good: 10, bad: 25 }, true)}`}>
                {result.maxDrawdownPercent.toFixed(1)}%
              </div>
            </div>
          </div>

          {/* Trade Statistics */}
          <div className="grid grid-cols-2 gap-4">
            <div className="p-4 bg-gray-900/50 rounded-lg">
              <h4 className="text-sm text-gray-400 mb-3">Trade Statistics</h4>
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Total Trades</span>
                  <span className="text-white">{result.totalTrades}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Winning</span>
                  <span className="text-green-400">{result.winningTrades}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Losing</span>
                  <span className="text-red-400">{result.losingTrades}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Avg Duration</span>
                  <span className="text-white">{formatDuration(result.avgTradeDuration)}</span>
                </div>
              </div>
            </div>

            <div className="p-4 bg-gray-900/50 rounded-lg">
              <h4 className="text-sm text-gray-400 mb-3">P&L Analysis</h4>
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Avg Win</span>
                  <span className="text-green-400">{formatCurrency(result.avgWin)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Avg Loss</span>
                  <span className="text-red-400">{formatCurrency(result.avgLoss)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Avg R:R</span>
                  <span className="text-white">1:{result.avgRR.toFixed(2)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Expectancy</span>
                  <span className={result.expectancy >= 0 ? 'text-green-400' : 'text-red-400'}>
                    {formatCurrency(result.expectancy)}
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Streaks & Extremes */}
          <div className="p-4 bg-gray-900/50 rounded-lg">
            <h4 className="text-sm text-gray-400 mb-3">Extremes & Streaks</h4>
            <div className="grid grid-cols-4 gap-4">
              <div className="text-center">
                <div className="text-green-400 font-bold">{formatCurrency(result.largestWin)}</div>
                <div className="text-xs text-gray-500">Largest Win</div>
              </div>
              <div className="text-center">
                <div className="text-red-400 font-bold">{formatCurrency(result.largestLoss)}</div>
                <div className="text-xs text-gray-500">Largest Loss</div>
              </div>
              <div className="text-center">
                <div className="text-green-400 font-bold">{result.longestWinStreak}</div>
                <div className="text-xs text-gray-500">Win Streak</div>
              </div>
              <div className="text-center">
                <div className="text-red-400 font-bold">{result.longestLoseStreak}</div>
                <div className="text-xs text-gray-500">Lose Streak</div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Trades Tab */}
      {activeTab === 'trades' && (
        <div>
          <div className="space-y-2 max-h-[400px] overflow-y-auto">
            {displayedTrades.map((trade) => {
              const isExpanded = expandedTradeId === trade.id;
              return (
                <div
                  key={trade.id}
                  onClick={() => {
                    setExpandedTradeId(isExpanded ? null : trade.id);
                    onTradeSelect?.(trade);
                  }}
                  className="p-3 bg-gray-900/50 rounded-lg border border-gray-700/50 cursor-pointer hover:border-gray-600 transition-colors"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className={`p-1.5 rounded ${trade.direction === 'BUY' ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
                        {trade.direction === 'BUY' ? (
                          <TrendingUp className="w-4 h-4 text-green-400" />
                        ) : (
                          <TrendingDown className="w-4 h-4 text-red-400" />
                        )}
                      </div>
                      <div>
                        <span className="font-medium text-white">{trade.symbol}</span>
                        <div className="text-xs text-gray-500">{formatDate(trade.entryTime)}</div>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <div className="text-right">
                        <div className={`font-mono font-medium ${trade.profit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                          {trade.profit >= 0 ? '+' : ''}{formatCurrency(trade.profit)}
                        </div>
                        <div className={`text-xs ${trade.profit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                          {formatPercent(trade.profitPercent)}
                        </div>
                      </div>
                      {isExpanded ? <ChevronUp className="w-4 h-4 text-gray-500" /> : <ChevronDown className="w-4 h-4 text-gray-500" />}
                    </div>
                  </div>

                  {isExpanded && (
                    <div className="mt-3 pt-3 border-t border-gray-700/50 grid grid-cols-4 gap-3 text-xs">
                      <div>
                        <span className="text-gray-500">Entry:</span>
                        <span className="text-white ml-1 font-mono">{trade.entryPrice.toFixed(5)}</span>
                      </div>
                      <div>
                        <span className="text-gray-500">Exit:</span>
                        <span className="text-white ml-1 font-mono">{trade.exitPrice.toFixed(5)}</span>
                      </div>
                      <div>
                        <span className="text-gray-500">Duration:</span>
                        <span className="text-white ml-1">{formatDuration(trade.duration)}</span>
                      </div>
                      <div>
                        <span className="text-gray-500">Exit:</span>
                        <span className="text-white ml-1">{formatDate(trade.exitTime)}</span>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          {result.trades.length > 10 && (
            <button
              onClick={() => setShowAllTrades(!showAllTrades)}
              className="w-full mt-3 py-2 text-sm text-blue-400 hover:text-blue-300 text-center"
            >
              {showAllTrades ? 'Show Less' : `Show All ${result.trades.length} Trades`}
            </button>
          )}
        </div>
      )}

      {/* Monthly Tab */}
      {activeTab === 'monthly' && result.monthlyReturns && (
        <div>
          <div className="grid grid-cols-4 gap-2">
            {Object.entries(result.monthlyReturns).map(([month, returns]) => (
              <div
                key={month}
                className={`p-3 rounded-lg text-center ${
                  returns >= 0 ? 'bg-green-500/10 border border-green-500/20' : 'bg-red-500/10 border border-red-500/20'
                }`}
              >
                <div className="text-xs text-gray-400 mb-1">{month}</div>
                <div className={`font-bold ${returns >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                  {formatPercent(returns)}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default BacktestResultsVisualization;
