import { useEffect, useRef } from "react";

const GraphVisualization: React.FC<{ points: Array<number>, min?: number, max?: number }> = ({ points, min, max }) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const minY = min ? min : Math.min(...points);
  const maxY = max ? max : Math.max(...points);

  useEffect(() => {

    const canvas = canvasRef.current;
    if (!canvas) {
      return;
    }

    const ctx = canvas.getContext('2d');
    if (!ctx) {
      return;
    }

    const backgroundColor = '#333333';
    const foregroundColor = '#FFA500';

    // clear

    ctx.fillStyle = backgroundColor;
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    // draw points

    ctx.fillStyle = foregroundColor;
    for (const [x, f] of points.entries()) {
      const yFract = 1 - (f - minY) / (maxY - minY);

      const y = yFract * ctx.canvas.height;

      ctx.fillRect(x, y, 1, 1);
    }

  }, [points]);

  return <><canvas ref={canvasRef} width={points.length} height={100} />{`${minY.toFixed(2)} - ${maxY.toFixed(2)}`}</>
}

export default GraphVisualization;
