import { useMemo } from 'react';
import Plot from 'react-plotly.js';

interface TrialData {
  trial_number: number;
  values: number[];
  constraint_satisfied?: boolean;
}

interface PlotlyFeasibilityChartProps {
  trials: TrialData[];
  height?: number;
}

export function PlotlyFeasibilityChart({
  trials,
  height = 350
}: PlotlyFeasibilityChartProps) {
  const { trialNumbers, cumulativeFeasibility, windowedFeasibility } = useMemo(() => {
    if (trials.length === 0) {
      return { trialNumbers: [], cumulativeFeasibility: [], windowedFeasibility: [] };
    }

    // Sort trials by number
    const sorted = [...trials].sort((a, b) => a.trial_number - b.trial_number);

    const numbers: number[] = [];
    const cumulative: number[] = [];
    const windowed: number[] = [];

    let feasibleCount = 0;
    const windowSize = Math.min(20, Math.floor(sorted.length / 5) || 1);

    sorted.forEach((trial, idx) => {
      numbers.push(trial.trial_number);

      // Cumulative feasibility
      if (trial.constraint_satisfied !== false) {
        feasibleCount++;
      }
      cumulative.push((feasibleCount / (idx + 1)) * 100);

      // Windowed (rolling) feasibility
      const windowStart = Math.max(0, idx - windowSize + 1);
      const windowTrials = sorted.slice(windowStart, idx + 1);
      const windowFeasible = windowTrials.filter(t => t.constraint_satisfied !== false).length;
      windowed.push((windowFeasible / windowTrials.length) * 100);
    });

    return { trialNumbers: numbers, cumulativeFeasibility: cumulative, windowedFeasibility: windowed };
  }, [trials]);

  if (trials.length === 0) {
    return (
      <div className="h-64 flex items-center justify-center text-dark-400">
        <p>No trials to display</p>
      </div>
    );
  }

  return (
    <Plot
      data={[
        {
          x: trialNumbers,
          y: cumulativeFeasibility,
          type: 'scatter',
          mode: 'lines',
          name: 'Cumulative Feasibility',
          line: { color: '#22c55e', width: 2 },
          hovertemplate: 'Trial %{x}<br>Cumulative: %{y:.1f}%<extra></extra>'
        },
        {
          x: trialNumbers,
          y: windowedFeasibility,
          type: 'scatter',
          mode: 'lines',
          name: 'Rolling (20-trial)',
          line: { color: '#60a5fa', width: 2, dash: 'dot' },
          hovertemplate: 'Trial %{x}<br>Rolling: %{y:.1f}%<extra></extra>'
        }
      ]}
      layout={{
        height,
        margin: { l: 60, r: 30, t: 30, b: 50 },
        paper_bgcolor: 'transparent',
        plot_bgcolor: 'transparent',
        xaxis: {
          title: { text: 'Trial Number', font: { color: '#888' } },
          tickfont: { color: '#888' },
          gridcolor: 'rgba(255,255,255,0.05)',
          zeroline: false
        },
        yaxis: {
          title: { text: 'Feasibility Rate (%)', font: { color: '#888' } },
          tickfont: { color: '#888' },
          gridcolor: 'rgba(255,255,255,0.1)',
          zeroline: false,
          range: [0, 105]
        },
        legend: {
          font: { color: '#888' },
          bgcolor: 'rgba(0,0,0,0.5)',
          x: 0.02,
          y: 0.98,
          xanchor: 'left',
          yanchor: 'top'
        },
        showlegend: true,
        hovermode: 'x unified'
      }}
      config={{
        displayModeBar: true,
        modeBarButtonsToRemove: ['lasso2d', 'select2d'],
        displaylogo: false
      }}
      style={{ width: '100%' }}
    />
  );
}
