/**
 * Strategy Comparison Chart
 * Compares performance of different trading strategies
 */

import React from 'react';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
  Legend,
} from 'recharts';
import type { StrategyPerformance } from '../../../services/backtestService';

interface StrategyComparisonChartProps {
  strategies: StrategyPerformance[];
  className?: string;
}

const STRATEGY_COLORS: Record<string, string> = {
  range_predictor: '#8b5cf6',
  amd_detector: '#06b6d4',
  ict_smc: '#f59e0b',
  tp_sl_classifier: '#ec4899',
  ensemble: '#22c55e',
};

export const StrategyComparisonChart: React.FC<StrategyComparisonChartProps> = ({
  strategies,
  className = '',
}) => {
  // Prepare data for bar chart
  const barData = strategies.map((s) => ({
    name: formatStrategyName(s.strategy),
    strategy: s.strategy,
    'Win Rate': s.win_rate,
    'Profit Factor': s.profit_factor,
    'Net Profit': s.net_profit,
    trades: s.trades,
    confidence: s.avg_confidence * 100,
  }));

  // Prepare data for radar chart (normalized 0-100)
  const radarData = [
    {
      metric: 'Win Rate',
      ...strategies.reduce((acc, s) => ({
        ...acc,
        [s.strategy]: s.win_rate,
      }), {}),
    },
    {
      metric: 'Profit Factor',
      ...strategies.reduce((acc, s) => ({
        ...acc,
        [s.strategy]: Math.min(s.profit_factor * 20, 100), // Scale PF to 0-100
      }), {}),
    },
    {
      metric: 'Trades',
      ...strategies.reduce((acc, s) => ({
        ...acc,
        [s.strategy]: Math.min((s.trades / Math.max(...strategies.map(st => st.trades))) * 100, 100),
      }), {}),
    },
    {
      metric: 'Confidence',
      ...strategies.reduce((acc, s) => ({
        ...acc,
        [s.strategy]: s.avg_confidence * 100,
      }), {}),
    },
    {
      metric: 'Profitability',
      ...strategies.reduce((acc, s) => {
        const maxProfit = Math.max(...strategies.map(st => st.net_profit));
        const minProfit = Math.min(...strategies.map(st => st.net_profit));
        const range = maxProfit - minProfit || 1;
        return {
          ...acc,
          [s.strategy]: ((s.net_profit - minProfit) / range) * 100,
        };
      }, {}),
    },
  ];

  function formatStrategyName(strategy: string): string {
    return strategy
      .replace(/_/g, ' ')
      .split(' ')
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ');
  }

  const CustomTooltip = ({ active, payload, label }: any) => {
    if (!active || !payload || !payload.length) return null;

    const data = payload[0].payload;

    return (
      <div className="bg-gray-900 border border-gray-700 rounded-lg p-3 shadow-lg">
        <p className="text-sm font-bold text-white mb-2">{data.name}</p>
        <div className="space-y-1 text-xs">
          <div className="flex justify-between gap-4">
            <span className="text-gray-400">Win Rate:</span>
            <span className={data['Win Rate'] >= 50 ? 'text-green-400' : 'text-red-400'}>
              {data['Win Rate'].toFixed(1)}%
            </span>
          </div>
          <div className="flex justify-between gap-4">
            <span className="text-gray-400">Profit Factor:</span>
            <span className={data['Profit Factor'] >= 1 ? 'text-green-400' : 'text-red-400'}>
              {data['Profit Factor'].toFixed(2)}
            </span>
          </div>
          <div className="flex justify-between gap-4">
            <span className="text-gray-400">Net Profit:</span>
            <span className={data['Net Profit'] >= 0 ? 'text-green-400' : 'text-red-400'}>
              ${data['Net Profit'].toFixed(2)}
            </span>
          </div>
          <div className="flex justify-between gap-4">
            <span className="text-gray-400">Trades:</span>
            <span className="text-white">{data.trades}</span>
          </div>
          <div className="flex justify-between gap-4">
            <span className="text-gray-400">Avg Confidence:</span>
            <span className="text-purple-400">{data.confidence.toFixed(1)}%</span>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className={`bg-gray-900 border border-gray-800 rounded-xl p-4 ${className}`}>
      <h3 className="text-lg font-bold text-white mb-4">Strategy Comparison</h3>

      {/* Strategy Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-5 gap-3 mb-6">
        {strategies.map((strategy) => (
          <div
            key={strategy.strategy}
            className="p-3 bg-gray-800 rounded-lg border-l-4"
            style={{ borderColor: STRATEGY_COLORS[strategy.strategy] || '#6b7280' }}
          >
            <p className="text-xs text-gray-400 mb-1">
              {formatStrategyName(strategy.strategy)}
            </p>
            <p className={`text-lg font-bold ${
              strategy.net_profit >= 0 ? 'text-green-400' : 'text-red-400'
            }`}>
              ${strategy.net_profit.toFixed(0)}
            </p>
            <div className="flex items-center justify-between mt-1 text-xs">
              <span className="text-gray-400">{strategy.trades} trades</span>
              <span className={strategy.win_rate >= 50 ? 'text-green-400' : 'text-red-400'}>
                {strategy.win_rate.toFixed(0)}%
              </span>
            </div>
          </div>
        ))}
      </div>

      {/* Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Bar Chart - Win Rate & Profit Factor */}
        <div>
          <h4 className="text-sm font-semibold text-gray-400 mb-3">Win Rate by Strategy</h4>
          <ResponsiveContainer width="100%" height={250}>
            <BarChart data={barData} layout="vertical" margin={{ left: 80 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#374151" />
              <XAxis type="number" domain={[0, 100]} stroke="#6b7280" tick={{ fontSize: 10 }} />
              <YAxis
                type="category"
                dataKey="name"
                stroke="#6b7280"
                tick={{ fontSize: 10 }}
              />
              <Tooltip content={<CustomTooltip />} />
              <Bar
                dataKey="Win Rate"
                fill="#8b5cf6"
                radius={[0, 4, 4, 0]}
              />
            </BarChart>
          </ResponsiveContainer>
        </div>

        {/* Radar Chart */}
        <div>
          <h4 className="text-sm font-semibold text-gray-400 mb-3">Multi-Metric Comparison</h4>
          <ResponsiveContainer width="100%" height={250}>
            <RadarChart data={radarData} margin={{ top: 10, right: 30, bottom: 10, left: 30 }}>
              <PolarGrid stroke="#374151" />
              <PolarAngleAxis dataKey="metric" tick={{ fontSize: 10, fill: '#9ca3af' }} />
              <PolarRadiusAxis
                angle={90}
                domain={[0, 100]}
                tick={{ fontSize: 8, fill: '#6b7280' }}
              />
              {strategies.map((strategy) => (
                <Radar
                  key={strategy.strategy}
                  name={formatStrategyName(strategy.strategy)}
                  dataKey={strategy.strategy}
                  stroke={STRATEGY_COLORS[strategy.strategy] || '#6b7280'}
                  fill={STRATEGY_COLORS[strategy.strategy] || '#6b7280'}
                  fillOpacity={0.2}
                  strokeWidth={2}
                />
              ))}
              <Legend
                wrapperStyle={{ fontSize: '10px' }}
                formatter={(value: string) => <span className="text-gray-400">{value}</span>}
              />
            </RadarChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* Detailed Table */}
      <div className="mt-6 overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="text-left text-gray-400 border-b border-gray-700">
              <th className="pb-2">Strategy</th>
              <th className="pb-2 text-right">Trades</th>
              <th className="pb-2 text-right">Win Rate</th>
              <th className="pb-2 text-right">Profit Factor</th>
              <th className="pb-2 text-right">Net Profit</th>
              <th className="pb-2 text-right">Avg Confidence</th>
            </tr>
          </thead>
          <tbody>
            {strategies.map((strategy) => (
              <tr key={strategy.strategy} className="border-b border-gray-800">
                <td className="py-2">
                  <div className="flex items-center gap-2">
                    <div
                      className="w-2 h-2 rounded-full"
                      style={{ backgroundColor: STRATEGY_COLORS[strategy.strategy] || '#6b7280' }}
                    />
                    <span className="text-white">{formatStrategyName(strategy.strategy)}</span>
                  </div>
                </td>
                <td className="py-2 text-right text-white">{strategy.trades}</td>
                <td className={`py-2 text-right font-bold ${
                  strategy.win_rate >= 50 ? 'text-green-400' : 'text-red-400'
                }`}>
                  {strategy.win_rate.toFixed(1)}%
                </td>
                <td className={`py-2 text-right font-bold ${
                  strategy.profit_factor >= 1 ? 'text-green-400' : 'text-red-400'
                }`}>
                  {strategy.profit_factor.toFixed(2)}
                </td>
                <td className={`py-2 text-right font-bold ${
                  strategy.net_profit >= 0 ? 'text-green-400' : 'text-red-400'
                }`}>
                  ${strategy.net_profit.toFixed(2)}
                </td>
                <td className="py-2 text-right text-purple-400">
                  {(strategy.avg_confidence * 100).toFixed(1)}%
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default StrategyComparisonChart;
