import { useRef, type RefObject } from "react";
import { Stage, Layer, Image, Rect } from "react-konva";
import { useCreateVideoSnapshot } from "../hooks/useGetvideoSnapshots";

const VideoFeedGridPainter = () => {
  const { latestBitmapRef } = useCreateVideoSnapshot();
  const isDrawing = useRef(false);

  const rows = 100;
  const cols = 100;
  const size = 10;
  const gap = 0;

  const squares = [];
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      squares.push(
        <Rect
          key={`${row}-${col}`}
          x={col * (size + gap)}
          y={row * (size + gap)}
          width={size}
          height={size}
          fill="#ddd"
          stroke="black"
          strokeWidth={0.5}
          opacity={0.5}
        />,
      );
    }
  }

  const getCoords = (e) => {
    isDrawing.current = true;
  };

  const handleMouseMove = (e) => {
    if (!isDrawing.current) {
      return;
    }
    const pos = e.target.getStage().getPointerPosition();
    console.log(pos);
  };

  const handleMouseUp = () => {
    isDrawing.current = false;
  };

  const draw = (bmp: RefObject<ImageBitmap | null>) => {
    if (!bmp || !bmp.current) {
      return;
    } else {
      const frame = bmp.current;
      return frame;
    }
  };

  return (
    <Stage
      width={640}
      height={360}
      onMouseDown={getCoords}
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
      onMouseLeave={handleMouseUp}
    >
      <Layer>
        <Image image={draw(latestBitmapRef)} width={640} height={360} />
      </Layer>
      <Layer opacity={0.3}>{squares}</Layer>
    </Stage>
  );
};

export default VideoFeedGridPainter;
