import React from 'react';
import Plot from 'react-plotly.js';
import {Backtest} from '../../../generated/ManagingApi';

interface TPvsSLvsPnL3DPlotProps {
  backtests: Backtest[];
  theme: { secondary: string };
}

const LOOPBACK_CONFIG = {
  singleIndicator: 1,
  multipleIndicators: { min: 5, max: 15 },
};

const TPvsSLvsPnL3DPlot: React.FC<TPvsSLvsPnL3DPlotProps> = ({ backtests, theme }) => {
  // Helper function to get generation from metadata
  const getGeneration = (backtest: Backtest): number => {
    if (backtest.metadata && typeof backtest.metadata === 'object' && 'generation' in backtest.metadata) {
      return (backtest.metadata as any).generation || 0;
    }
    return 0;
  };

  // Helper function to get indicator details from config
  const getIndicatorDetails = (backtest: Backtest): string => {
    if (!backtest.config.scenario?.indicators) return 'Unknown';
    
    return backtest.config.scenario.indicators.map((indicator: any) => {
      let details = indicator.type?.toString() || 'Unknown';
      if (indicator.period) details += ` (${indicator.period})`;
      if (indicator.fastPeriods && indicator.slowPeriods) details += ` (${indicator.fastPeriods}/${indicator.slowPeriods})`;
      if (indicator.multiplier) details += ` (${indicator.multiplier.toFixed(1)}x)`;
      return details;
    }).join(', ');
  };

  const plotDataTPvsSL = backtests.length > 0 ? [
    {
      type: 'scatter3d' as const,
      mode: 'markers' as const,
      x: backtests.map(b => b.config.moneyManagement?.takeProfit || 0),
      y: backtests.map(b => b.config.moneyManagement?.stopLoss || 0),
      z: backtests.map(b => b.statistics?.totalPnL || 0),
      marker: {
        size: 5,
        color: backtests.map(b => {
          const pnl = b.statistics?.totalPnL || 0;
          return pnl > 0 ? pnl : 0;
        }),
        colorscale: 'RdYlGn' as const,
        opacity: 0.8,
        colorbar: {
          title: 'PnL ($)',
          titleside: 'right',
        },
      },
      text: backtests.map(b => {
        const generation = getGeneration(b);
        const indicatorDetails = getIndicatorDetails(b);
        const riskRewardRatio = (b.config.moneyManagement?.takeProfit || 0) / (b.config.moneyManagement?.stopLoss || 1);
        const riskRewardColor = riskRewardRatio >= 2 ? '🟢' : riskRewardRatio >= 1.5 ? '🟡' : '🔴';
        const maxDrawdownPc = Math.abs(b.statistics?.maxDrawdownPc || 0);
        const drawdownColor = maxDrawdownPc <= 10 ? '🟢' : maxDrawdownPc <= 25 ? '🟡' : '🔴';
        
        return `Generation: ${generation}<br>` +
               `PnL: $${b.statistics?.totalPnL?.toFixed(2) || 'N/A'}<br>` +
               `Win Rate: ${b.winRate?.toFixed(1) || 'N/A'}%<br>` +
               `Max Drawdown: ${drawdownColor} ${maxDrawdownPc.toFixed(1)}%<br>` +
               `SL: ${b.config.moneyManagement?.stopLoss?.toFixed(1) || 'N/A'}%<br>` +
               `TP: ${b.config.moneyManagement?.takeProfit?.toFixed(1) || 'N/A'}%<br>` +
               `R/R: ${riskRewardColor} ${riskRewardRatio.toFixed(2)}<br>` +
               `Leverage: ${b.config.moneyManagement?.leverage || 1}x<br>` +
               `Cooldown: ${b.config.cooldownPeriod || 0} candles<br>` +
               `Max Loss Streak: ${b.config.maxLossStreak || 0}<br>` +
               `Max Time: ${b.config.maxPositionTimeHours || 0}h<br>` +
               `Indicators: ${indicatorDetails}<br>` +
               `Loopback: ${b.config.scenario?.loopbackPeriod || 'Unknown'}`;
      }),
      hovertemplate: '%{text}<extra></extra>',
    },
  ] : [];

  return (
    <Plot
      data={plotDataTPvsSL}
      layout={{
        title: {text: 'Take Profit % vs Stop Loss % vs PnL'},
        scene: {
          xaxis: {title: {text: 'Take Profit (%)'}, zerolinecolor: theme.secondary, color: theme.secondary},
          yaxis: {title: {text: 'Stop Loss (%)'}, zerolinecolor: theme.secondary, color: theme.secondary},
          zaxis: {title: {text: 'PnL ($)'}, zerolinecolor: theme.secondary, color: theme.secondary},
        },
        width: 750,
        height: 600,
        margin: {
          b: 20,
          l: 0,
          pad: 0,
          r: 0,
          t: 0,
        },
        paper_bgcolor: "rgba(0,0,0,0)",
        plot_bgcolor: "rgba(0,0,0,0)",
      }}
      config={{displayModeBar: false}}
    />
  );
};

export default TPvsSLvsPnL3DPlot; 