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

interface ScoreVsGenerationProps {
  backtests: Backtest[]
  theme: { secondary: string }
}

const ScoreVsGeneration: React.FC<ScoreVsGenerationProps> = ({ backtests }) => {
    const theme = useTheme().themeProperty()

  // 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 score from backtest
  const getScore = (backtest: Backtest): number => {
    return backtest.score || 0
  }

  // Prepare data for the chart
  const chartData = backtests.length > 0 ? [
    {
      type: 'scatter' as const,
      mode: 'lines+markers' as const,
      x: backtests.map(backtest => getGeneration(backtest)),
      y: backtests.map(backtest => getScore(backtest)),
      marker: {
        size: 8,
        color: backtests.map(backtest => {
          const score = getScore(backtest)
          // Color gradient: red for low score, yellow for medium, green for high
          if (score < 0.3) return '#ff4444' // Red
          if (score < 0.6) return '#ffaa00' // Yellow/Orange
          return '#00aa44' // Green
        }),
        opacity: 0.8,
        line: {
          color: theme.secondary,
          width: 1
        }
      },
      line: {
        color: theme.secondary,
        width: 2,
        opacity: 0.6
      },
      text: backtests.map(backtest => {
        const score = getScore(backtest)
        const generation = getGeneration(backtest)
        const pnl = backtest.statistics?.totalPnL || 0
        const winRate = backtest.winRate || 0
        const maxDrawdown = Math.abs(backtest.statistics?.maxDrawdownPc || 0)
        
        return `Generation: ${generation}<br>` +
               `Score: ${score.toFixed(3)}<br>` +
               `PnL: $${pnl.toFixed(2)}<br>` +
               `Win Rate: ${winRate.toFixed(1)}%<br>` +
               `Max Drawdown: ${maxDrawdown.toFixed(1)}%<br>` +
               `Ticker: ${backtest.config?.ticker || 'N/A'}<br>` +
               `Timeframe: ${backtest.config?.timeframe || 'N/A'}`
      }),
      hovertemplate: '%{text}<extra></extra>',
      name: 'Score'
    }
  ] : []

  // Calculate trend line if we have enough data points
  const trendLineData = backtests.length > 2 ? (() => {
    const generations = backtests.map(backtest => getGeneration(backtest))
    const scores = backtests.map(backtest => getScore(backtest))
    
    // Simple linear regression
    const n = generations.length
    const sumX = generations.reduce((sum, x) => sum + x, 0)
    const sumY = scores.reduce((sum, y) => sum + y, 0)
    const sumXY = generations.reduce((sum, x, i) => sum + x * scores[i], 0)
    const sumXX = generations.reduce((sum, x) => sum + x * x, 0)
    
    const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX)
    const intercept = (sumY - slope * sumX) / n
    
    const minGen = Math.min(...generations)
    const maxGen = Math.max(...generations)
    
    return [{
      type: 'scatter' as const,
      mode: 'lines' as const,
      x: [minGen, maxGen],
      y: [slope * minGen + intercept, slope * maxGen + intercept],
      line: {
        color: '#888888',
        width: 2,
        dash: 'dash' as const
      },
      name: 'Trend Line',
      showlegend: true
    }]
  })() : []

  const layout = {
    title: {
      text: 'Score vs Generation',
      font: {
        color: theme.secondary
      }
    },
    xaxis: {
      title: {
        text: 'Generation Number',
        font: {
          color: theme.secondary
        }
      },
      gridcolor: theme.neutral,
      zerolinecolor: theme.secondary,
      color: theme.secondary
    },
    yaxis: {
      title: {
        text: 'Score',
        font: {
          color: theme.secondary
        }
      },
      gridcolor: theme.neutral,
      zerolinecolor: theme.secondary,
      color: theme.secondary
    },
    plot_bgcolor: 'rgba(0,0,0,0)',
    paper_bgcolor: 'rgba(0,0,0,0)',
    font: {
      color: theme.secondary
    },
    legend: {
      font: {
        color: theme.secondary
      }
    },
    margin: {
      l: 60,
      r: 30,
      t: 60,
      b: 60
    }
  }

  const config = {
    displayModeBar: true,
    displaylogo: false,
    responsive: true
  }

  return (
    <div className="w-full h-96">
      <Plot
        data={[...chartData, ...trendLineData]}
        layout={layout}
        config={config}
        style={{ width: '100%', height: '100%' }}
        useResizeHandler={true}
      />
    </div>
  )
}

export default ScoreVsGeneration 