import type { BacktestResult } from '../types/backtest.types';
import { useState, useMemo, memo } from 'react';
import { Chart } from '../../../components/charts/Chart';
import { ChartContainer } from './ChartContainer';

interface BacktestChartProps {
  result: BacktestResult | null;
  isLoading: boolean;
}

// Memoize the component to prevent unnecessary re-renders
export const BacktestChart = memo(function BacktestChart({ result, isLoading }: BacktestChartProps) {
  const [selectedSymbol, setSelectedSymbol] = useState<string>('');

  const chartData = useMemo(() => {
    if (!result?.equity || !result?.ohlcData) return null;

    const symbols = Object.keys(result.ohlcData);
    const symbol = selectedSymbol || symbols[0] || '';
    const ohlcData = result.ohlcData[symbol] || [];
    
    // Remove excessive logging in production
    // Log only on significant changes
    if (process.env.NODE_ENV === 'development' && ohlcData.length > 0) {
      // Use a simple hash to detect actual data changes
      const dataHash = `${symbols.length}-${result.equity?.length}-${ohlcData.length}`;
      if ((window as any).__lastDataHash !== dataHash) {
        (window as any).__lastDataHash = dataHash;
        console.log('BacktestChart data updated:', {
          symbols,
          selectedSymbol,
          symbol,
          ohlcDataKeys: Object.keys(result.ohlcData),
          equityLength: result.equity?.length,
          tradesLength: result.trades?.length
        });
      }
    }
    
    const equityData = (result.equity || [])
      .filter(e => e && e.date && e.value != null)
      .map(e => ({
        time: new Date(e.date).getTime() / 1000,
        value: e.value
      }));

    // Find trades for this symbol
    const symbolTrades = result.trades?.filter(t => t.symbol === symbol) || [];
    console.log('Symbol trades for', symbol, ':', symbolTrades);
    
    const tradeMarkers = symbolTrades
      .filter(trade => {
        // Check multiple possible field names
        const hasPrice = trade.price != null || trade.entryPrice != null;
        const hasTime = trade.timestamp != null || trade.entryDate != null || trade.date != null;
        return hasPrice && hasTime;
      })
      .map(trade => {
        // Use whatever field names are present
        const price = trade.price || trade.entryPrice;
        const timestamp = trade.timestamp || trade.entryDate || trade.date;
        const side = trade.side || (trade.quantity > 0 ? 'buy' : 'sell');
        
        return {
          time: new Date(timestamp).getTime() / 1000,
          position: 'belowBar' as const,
          color: side === 'buy' ? '#10b981' : '#ef4444',
          shape: (side === 'buy' ? 'arrowUp' : 'arrowDown') as const,
          text: `${side === 'buy' ? 'Buy' : 'Sell'} @ $${price.toFixed(2)}`,
          price: price
        };
      });
    
    console.log('Trade markers:', tradeMarkers);

    const processedOhlcData = ohlcData
      .filter(d => d && d.timestamp != null && d.open != null && d.high != null && d.low != null && d.close != null)
      .map(d => ({
        time: d.timestamp / 1000,  // timestamp is already in milliseconds
        open: d.open,
        high: d.high,
        low: d.low,
        close: d.close,
        volume: d.volume || 0
      }));
    
    return {
      ohlcData: processedOhlcData,
      equityData,
      tradeMarkers,
      symbols
    };
  }, [result, selectedSymbol]);

  if (isLoading) {
    return (
      <div className="bg-surface-secondary rounded-lg border border-border p-4 h-full animate-pulse">
        <div className="h-full bg-surface rounded"></div>
      </div>
    );
  }

  if (!result || !chartData) {
    return (
      <div className="bg-surface-secondary rounded-lg border border-border p-8 text-center h-full flex items-center justify-center">
        <p className="text-text-secondary">Run a backtest to see the equity curve and price chart.</p>
      </div>
    );
  }

  return (
    <div className="h-full flex flex-col">
      {chartData.symbols.length > 1 && (
        <div className="flex space-x-2 mb-4">
          <label className="text-sm text-text-secondary">Symbol:</label>
          <select
            value={selectedSymbol || chartData.symbols[0]}
            onChange={(e) => setSelectedSymbol(e.target.value)}
            className="px-2 py-1 bg-background border border-border rounded text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
          >
            {chartData.symbols.map(symbol => (
              <option key={symbol} value={symbol}>{symbol}</option>
            ))}
          </select>
        </div>
      )}
      
      <div className="flex-1 min-h-0">
        <ChartContainer>
          {(height) => (
            <Chart
              data={chartData.ohlcData}
              overlayData={[
                {
                  name: 'Equity',
                  data: chartData.equityData,
                  color: '#3b82f6',
                  lineWidth: 2
                }
              ]}
              tradeMarkers={chartData.tradeMarkers}
              height={height}
              chartId={`backtest-${result?.runId || 'default'}`}
              key={result?.runId || 'default'}
            />
          )}
        </ChartContainer>
      </div>
    </div>
  );
});