import { useEffect, useRef, useState } from "react";

export default function TradingGraph() {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [data, setData] = useState<number[]>([]);

  // Generate sample data for demo
  useEffect(() => {
    const generateData = () => {
      const points = 50;
      const newData: number[] = [];
      let value = 100;
      
      for (let i = 0; i < points; i++) {
        value += (Math.random() - 0.45) * 5;
        newData.push(Math.max(50, Math.min(150, value)));
      }
      
      setData(newData);
    };

    generateData();
    const interval = setInterval(generateData, 5000);
    return () => clearInterval(interval);
  }, []);

  // Draw the graph
  useEffect(() => {
    if (!canvasRef.current || data.length === 0) return;

    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    // Get CSS variables
    const styles = getComputedStyle(document.documentElement);
    const colorOther = styles.getPropertyValue("--c-other").trim();
    const colorLines = styles.getPropertyValue("--c-lines").trim();
    const colorBoxes = styles.getPropertyValue("--c-boxes").trim();

    // Set canvas size
    const rect = canvas.getBoundingClientRect();
    canvas.width = rect.width * window.devicePixelRatio;
    canvas.height = rect.height * window.devicePixelRatio;
    ctx.scale(window.devicePixelRatio, window.devicePixelRatio);

    const width = rect.width;
    const height = rect.height;
    const padding = 40;

    // Clear canvas
    ctx.clearRect(0, 0, width, height);

    // Draw grid
    ctx.strokeStyle = colorLines;
    ctx.lineWidth = 0.5;
    ctx.globalAlpha = 0.2;
    
    // Horizontal grid lines
    for (let i = 0; i <= 5; i++) {
      const y = padding + (height - 2 * padding) * (i / 5);
      ctx.beginPath();
      ctx.moveTo(padding, y);
      ctx.lineTo(width - padding, y);
      ctx.stroke();
    }

    // Vertical grid lines
    for (let i = 0; i <= 10; i++) {
      const x = padding + (width - 2 * padding) * (i / 10);
      ctx.beginPath();
      ctx.moveTo(x, padding);
      ctx.lineTo(x, height - padding);
      ctx.stroke();
    }

    ctx.globalAlpha = 1;

    // Find min and max values
    const minValue = Math.min(...data);
    const maxValue = Math.max(...data);
    const range = maxValue - minValue || 1;

    // Draw the line graph
    ctx.strokeStyle = colorOther;
    ctx.lineWidth = 3; // Thicker line
    ctx.lineJoin = "round";
    ctx.lineCap = "round";

    ctx.beginPath();
    data.forEach((value, index) => {
      const x = padding + (width - 2 * padding) * (index / (data.length - 1));
      const y = height - padding - (height - 2 * padding) * ((value - minValue) / range);

      if (index === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
    });
    ctx.stroke();

    // Draw area under the line with gradient
    const gradient = ctx.createLinearGradient(0, padding, 0, height - padding);
    gradient.addColorStop(0, colorBoxes + "80");
    gradient.addColorStop(1, colorBoxes + "00");
    
    ctx.fillStyle = gradient;
    ctx.lineTo(width - padding, height - padding);
    ctx.lineTo(padding, height - padding);
    ctx.closePath();
    ctx.fill();

    // Draw data points
    ctx.fillStyle = colorOther;
    data.forEach((value, index) => {
      const x = padding + (width - 2 * padding) * (index / (data.length - 1));
      const y = height - padding - (height - 2 * padding) * ((value - minValue) / range);

      ctx.beginPath();
      ctx.arc(x, y, 4, 0, Math.PI * 2);
      ctx.fill();
    });

    // Draw labels
    ctx.fillStyle = colorLines;
    ctx.font = "12px Inter, sans-serif";
    ctx.textAlign = "right";
    
    // Y-axis labels
    for (let i = 0; i <= 5; i++) {
      const value = maxValue - (range * i / 5);
      const y = padding + (height - 2 * padding) * (i / 5);
      ctx.fillText(value.toFixed(0), padding - 10, y + 4);
    }

  }, [data]);

  return (
    <section id="live" className="py-20 bg-gradient-to-b from-brand-bg to-brand-bgLight">
      <div className="container mx-auto px-4">
        <h2 className="text-3xl md:text-4xl font-bold mb-6 text-rainbow">Live Performance</h2>
        <div className="card p-4 md:p-6">
          <div className="mb-3 text-sm text-brand-text/60">Trading212 Performance Chart</div>
          <div className="aspect-[16/9] w-full rounded border border-brand-lines/50 bg-brand-bg/40 overflow-hidden">
            <canvas
              ref={canvasRef}
              className="w-full h-full"
              style={{ display: "block" }}
            />
          </div>
        </div>
      </div>
    </section>
  );
}