import { useRef, type RefObject } from "react";
import { Stage, Layer, Image, Shape } from "react-konva";
import type { KonvaEventObject } from "konva/lib/Node";
import { useCreateVideoSnapshot } from "../hooks/useGetvideoSnapshots";
import Card from "../../../ui/Card";
import type { Region } from "../../../types/types";

const rows = 40;
const cols = 40;
const size = 20;
const gap = 0;

type VideoFeedGridPainterProps = {
  regions: Region[];
  selectedRegionIndex: number;
  isErasing: boolean;
};

type PaintedCell = {
  colour: string;
};

const VideoFeedGridPainter = ({ regions, selectedRegionIndex, isErasing }: VideoFeedGridPainterProps) => {
  const { latestBitmapRef } = useCreateVideoSnapshot();
  const isDrawingRef = useRef(false);
  const paintedCellsRef = useRef<Map<string, PaintedCell>>(new Map());
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const paintLayerRef = useRef<any>(null);

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

  const paintCell = (x: number, y: number) => {
    const col = Math.floor(x / (size + gap));
    const row = Math.floor(y / (size + gap));

    if (row < 0 || row >= rows || col < 0 || col >= cols) return;

    const activeRegion = regions[selectedRegionIndex];
    if (!activeRegion) return;

    const key = `${row}-${col}`;
    const currentColour = regions[selectedRegionIndex].brushColour;

    const map = paintedCellsRef.current;
    const existing = map.get(key);

    if (isErasing) {
      if (map.has(key)) {
        map.delete(key);
        paintLayerRef.current?.batchDraw();
      }
      return;
    }

    if (existing && existing.colour === currentColour) return;

    map.set(key, { colour: currentColour });

    paintLayerRef.current?.batchDraw();
  };

  const handleStageMouseDown = (e: KonvaEventObject<MouseEvent>) => {
    if (!regions[selectedRegionIndex]) return;
    isDrawingRef.current = true;
    const pos = e.target.getStage()?.getPointerPosition();
    if (pos) paintCell(pos.x, pos.y);
  };

  const handleStageMouseMove = (e: KonvaEventObject<MouseEvent>) => {
    if (!isDrawingRef.current) return;
    if (!regions[selectedRegionIndex]) return;
    const pos = e.target.getStage()?.getPointerPosition();
    if (pos) paintCell(pos.x, pos.y);
  };

  const handleStageMouseUp = () => {
    isDrawingRef.current = false;
  };

  return (
    <Card className="w-187.5 place-self-start">
      <Stage
        width={740}
        height={460}
        onMouseDown={handleStageMouseDown}
        onMouseMove={handleStageMouseMove}
        onMouseUp={handleStageMouseUp}
        onMouseLeave={handleStageMouseUp}
      >
        <Layer>
          <Image image={draw(latestBitmapRef)} width={740} height={460} />
        </Layer>

        <Layer ref={paintLayerRef} opacity={0.6}>
          <Shape
            sceneFunc={(ctx, shape) => {
              const cells = paintedCellsRef.current;
              cells.forEach((cell, key) => {
                const [rowStr, colStr] = key.split("-");
                const row = Number(rowStr);
                const col = Number(colStr);

                const x = col * (size + gap);
                const y = row * (size + gap);

                ctx.beginPath();
                ctx.rect(x, y, size, size);
                ctx.fillStyle = cell.colour;
                ctx.fill();
              });

              ctx.fillStrokeShape(shape);
            }}
          />
        </Layer>
      </Stage>
    </Card>
  );
};

export default VideoFeedGridPainter;
