import React, { useMemo } from 'react';

interface ProbabilityChartProps {
  strategy: 'naive' | 'loop';
}

const ProbabilityChart: React.FC<ProbabilityChartProps> = ({ strategy }) => {
  const data = useMemo(() => {
    const points = [];
    const maxN = 50;
    
    for (let n = 2; n <= maxN; n += 2) {
      let probability;
      
      if (strategy === 'naive') {
        // Naive strategy: (1/2)^n
        probability = Math.pow(0.5, n);
      } else {
        // Loop strategy: 1 - sum(1/k for k from n/2+1 to n)
        let sum = 0;
        for (let k = Math.floor(n / 2) + 1; k <= n; k++) {
          sum += 1 / k;
        }
        probability = 1 - sum;
      }
      
      points.push({ n, probability });
    }
    
    return points;
  }, [strategy]);

  // Find min and max for scaling
  const maxProb = Math.max(...data.map(d => d.probability));
  const minProb = Math.min(...data.map(d => d.probability));
  
  // Use log scale for naive strategy since values get extremely small
  const useLogScale = strategy === 'naive';
  
  const getY = (prob: number, height: number) => {
    if (useLogScale) {
      const logProb = prob > 0 ? Math.log10(prob) : -100;
      const logMax = Math.log10(maxProb);
      const logMin = Math.log10(minProb);
      return height - ((logProb - logMin) / (logMax - logMin)) * height;
    } else {
      return height - (prob / maxProb) * height;
    }
  };

  const chartWidth = 600;
  const chartHeight = 300;
  const padding = { top: 20, right: 20, bottom: 50, left: 70 };
  const width = chartWidth - padding.left - padding.right;
  const height = chartHeight - padding.top - padding.bottom;

  // Create path for the line
  const pathData = data.map((point, i) => {
    const x = (point.n / 50) * width;
    const y = getY(point.probability, height);
    return `${i === 0 ? 'M' : 'L'} ${x} ${y}`;
  }).join(' ');

  // Y-axis labels
  const yLabels = useLogScale
    ? [-5, -10, -15, -20, -25, -30].map(exp => ({
        label: `10^${exp}`,
        value: Math.pow(10, exp),
      }))
    : [0, 0.1, 0.2, 0.3, 0.4, 0.5].map(val => ({
        label: val.toFixed(1),
        value: val,
      }));

  return (
    <div className="my-8 p-6 border-2 border-gray-300 rounded-lg bg-white">
      <h3 className="text-xl font-semibold mb-4">
        {strategy === 'naive' ? 'Naive Strategy: Random Box Selection' : 'Loop Strategy'}
      </h3>
      
      <svg width={chartWidth} height={chartHeight} className="mx-auto">
        <g transform={`translate(${padding.left}, ${padding.top})`}>
          {/* Grid lines */}
          {yLabels.map(({ value }) => {
            const y = getY(value, height);
            return (
              <line
                key={value}
                x1={0}
                y1={y}
                x2={width}
                y2={y}
                stroke="#e5e7eb"
                strokeWidth={1}
              />
            );
          })}

          {/* X-axis */}
          <line
            x1={0}
            y1={height}
            x2={width}
            y2={height}
            stroke="#374151"
            strokeWidth={2}
          />

          {/* Y-axis */}
          <line
            x1={0}
            y1={0}
            x2={0}
            y2={height}
            stroke="#374151"
            strokeWidth={2}
          />

          {/* Plot line */}
          <path
            d={pathData}
            fill="none"
            stroke="#3b82f6"
            strokeWidth={3}
            strokeLinecap="round"
            strokeLinejoin="round"
          />

          {/* Data points */}
          {data.filter((_, i) => i % 2 === 0).map((point) => {
            const x = (point.n / 50) * width;
            const y = getY(point.probability, height);
            return (
              <circle
                key={point.n}
                cx={x}
                cy={y}
                r={4}
                fill="#3b82f6"
              />
            );
          })}

          {/* X-axis labels */}
          {[10, 20, 30, 40, 50].map((n) => {
            const x = (n / 50) * width;
            return (
              <text
                key={n}
                x={x}
                y={height + 25}
                textAnchor="middle"
                fontSize="14"
                fill="#374151"
              >
                {n}
              </text>
            );
          })}

          {/* Y-axis labels */}
          {yLabels.map(({ label, value }) => {
            const y = getY(value, height);
            return (
              <text
                key={value}
                x={-10}
                y={y + 5}
                textAnchor="end"
                fontSize="12"
                fill="#374151"
              >
                {label}
              </text>
            );
          })}

          {/* X-axis title */}
          <text
            x={width / 2}
            y={height + 45}
            textAnchor="middle"
            fontSize="16"
            fontWeight="600"
            fill="#374151"
          >
            Number of Prisoners (n)
          </text>

          {/* Y-axis title */}
          <text
            x={-height / 2}
            y={-50}
            textAnchor="middle"
            fontSize="16"
            fontWeight="600"
            fill="#374151"
            transform={`rotate(-90, ${-height / 2}, -50)`}
          >
            Probability of Success
          </text>
        </g>
      </svg>

      <div className="mt-4 p-4 bg-gray-100 rounded">
        <p className="text-sm">
          {strategy === 'naive' ? (
            <>
              The naive strategy has probability <strong>(1/2)^n</strong> which decreases 
              exponentially. Note the logarithmic scale on the y-axis! 
              With 20 prisoners, the probability is already less than one in a million.
            </>
          ) : (
            <>
              The loop strategy maintains a probability around <strong>31%</strong> regardless 
              of the number of prisoners, approaching 1 - ln(2) ≈ 0.3069 as n → ∞.
            </>
          )}
        </p>
      </div>
    </div>
  );
};

export default ProbabilityChart;
