/**
 * Equity Curve Chart Component
 * Displays equity curve with drawdown visualization
 */

import React, { useMemo } from 'react';
import {
  ComposedChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  ReferenceLine,
  Bar,
  Cell,
} from 'recharts';
import type { EquityPoint, BacktestTrade } from '../../../services/backtestService';

interface EquityCurveChartProps {
  equityCurve: EquityPoint[];
  trades: BacktestTrade[];
  initialCapital: number;
  height?: number;
  showDrawdown?: boolean;
  showTrades?: boolean;
  className?: string;
}

export const EquityCurveChart: React.FC<EquityCurveChartProps> = ({
  equityCurve,
  trades,
  initialCapital,
  height = 300,
  showDrawdown = true,
  showTrades = true,
  className = '',
}) => {
  // Process data for chart
  const chartData = useMemo(() => {
    // Create trade lookup by timestamp
    const tradeMap = new Map<string, BacktestTrade>();
    trades.forEach((trade) => {
      if (trade.exit_time) {
        const key = trade.exit_time.slice(0, 10);
        tradeMap.set(key, trade);
      }
    });

    return equityCurve.map((point) => {
      const dateKey = point.timestamp.slice(0, 10);
      const trade = tradeMap.get(dateKey);

      return {
        ...point,
        date: new Date(point.timestamp).toLocaleDateString(),
        returnPct: ((point.equity - initialCapital) / initialCapital) * 100,
        tradeResult: trade?.pnl,
        isWin: trade?.pnl ? trade.pnl > 0 : undefined,
      };
    });
  }, [equityCurve, trades, initialCapital]);

  // Calculate statistics
  const { maxEquity, minEquity, maxDrawdownPct } = useMemo(() => {
    let max = -Infinity;
    let min = Infinity;
    let maxDD = 0;

    chartData.forEach((d) => {
      max = Math.max(max, d.equity);
      min = Math.min(min, d.equity);
      maxDD = Math.max(maxDD, Math.abs(d.drawdown_percent));
    });

    return { maxEquity: max, minEquity: min, maxDrawdownPct: maxDD };
  }, [chartData]);

  // Custom tooltip
  const CustomTooltip = ({ active, payload }: 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-xs text-gray-400 mb-2">{data.date}</p>
        <div className="space-y-1 text-xs">
          <div className="flex justify-between gap-4">
            <span className="text-gray-400">Equity:</span>
            <span className="text-white font-bold">
              ${data.equity.toLocaleString(undefined, { minimumFractionDigits: 2 })}
            </span>
          </div>
          <div className="flex justify-between gap-4">
            <span className="text-gray-400">Return:</span>
            <span className={data.returnPct >= 0 ? 'text-green-400' : 'text-red-400'}>
              {data.returnPct >= 0 ? '+' : ''}{data.returnPct.toFixed(2)}%
            </span>
          </div>
          {showDrawdown && (
            <div className="flex justify-between gap-4">
              <span className="text-gray-400">Drawdown:</span>
              <span className="text-red-400">
                {data.drawdown_percent > 0 ? '-' : ''}{data.drawdown_percent.toFixed(2)}%
              </span>
            </div>
          )}
          {data.tradeResult !== undefined && (
            <div className="flex justify-between gap-4 pt-1 border-t border-gray-700">
              <span className="text-gray-400">Trade P/L:</span>
              <span className={data.isWin ? 'text-green-400' : 'text-red-400'}>
                ${data.tradeResult.toFixed(2)}
              </span>
            </div>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className={`bg-gray-900 border border-gray-800 rounded-xl p-4 ${className}`}>
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-bold text-white">Equity Curve</h3>
        <div className="flex items-center gap-4 text-xs">
          <div className="flex items-center gap-1">
            <div className="w-3 h-3 bg-green-500 rounded" />
            <span className="text-gray-400">Equity</span>
          </div>
          {showDrawdown && (
            <div className="flex items-center gap-1">
              <div className="w-3 h-3 bg-red-500/30 rounded" />
              <span className="text-gray-400">Drawdown</span>
            </div>
          )}
        </div>
      </div>

      {/* Stats bar */}
      <div className="grid grid-cols-4 gap-2 mb-4">
        <div className="p-2 bg-gray-800 rounded text-center">
          <p className="text-xs text-gray-400">Initial</p>
          <p className="text-sm font-bold text-white">
            ${initialCapital.toLocaleString()}
          </p>
        </div>
        <div className="p-2 bg-gray-800 rounded text-center">
          <p className="text-xs text-gray-400">Final</p>
          <p className={`text-sm font-bold ${chartData[chartData.length - 1]?.equity >= initialCapital ? 'text-green-400' : 'text-red-400'}`}>
            ${chartData[chartData.length - 1]?.equity.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </p>
        </div>
        <div className="p-2 bg-gray-800 rounded text-center">
          <p className="text-xs text-gray-400">Peak</p>
          <p className="text-sm font-bold text-green-400">
            ${maxEquity.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </p>
        </div>
        <div className="p-2 bg-gray-800 rounded text-center">
          <p className="text-xs text-gray-400">Max DD</p>
          <p className="text-sm font-bold text-red-400">
            -{maxDrawdownPct.toFixed(2)}%
          </p>
        </div>
      </div>

      <ResponsiveContainer width="100%" height={height}>
        <ComposedChart data={chartData} margin={{ top: 10, right: 30, left: 10, bottom: 10 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="#374151" />
          <XAxis
            dataKey="date"
            stroke="#6b7280"
            tick={{ fontSize: 10 }}
            interval="preserveStartEnd"
          />
          <YAxis
            yAxisId="equity"
            domain={['auto', 'auto']}
            stroke="#6b7280"
            tick={{ fontSize: 10 }}
            tickFormatter={(value: number) => `$${(value / 1000).toFixed(0)}k`}
          />
          {showDrawdown && (
            <YAxis
              yAxisId="drawdown"
              orientation="right"
              domain={[0, maxDrawdownPct * 1.5]}
              stroke="#ef4444"
              tick={{ fontSize: 10 }}
              tickFormatter={(value: number) => `-${value.toFixed(0)}%`}
            />
          )}
          <Tooltip content={<CustomTooltip />} />

          {/* Initial capital reference */}
          <ReferenceLine
            yAxisId="equity"
            y={initialCapital}
            stroke="#6b7280"
            strokeDasharray="5 5"
            label={{ value: 'Initial', position: 'left', fontSize: 10, fill: '#6b7280' }}
          />

          {/* Drawdown area */}
          {showDrawdown && (
            <Area
              yAxisId="drawdown"
              type="monotone"
              dataKey="drawdown_percent"
              stroke="#ef4444"
              fill="#ef4444"
              fillOpacity={0.2}
              strokeWidth={1}
            />
          )}

          {/* Equity line */}
          <Area
            yAxisId="equity"
            type="monotone"
            dataKey="equity"
            stroke="#22c55e"
            fill="#22c55e"
            fillOpacity={0.1}
            strokeWidth={2}
          />

          {/* Trade markers */}
          {showTrades && chartData.some((d) => d.tradeResult !== undefined) && (
            <Bar
              yAxisId="equity"
              dataKey="tradeResult"
              opacity={0.5}
              barSize={3}
            >
              {chartData.map((entry, index) => (
                <Cell key={`cell-${index}`} fill={entry.isWin ? '#22c55e' : '#ef4444'} />
              ))}
            </Bar>
          )}
        </ComposedChart>
      </ResponsiveContainer>
    </div>
  );
};

export default EquityCurveChart;
