import { Stage, Layer, Image, Rect } from "react-konva";
import type { SightingType } from "../../../../utils/types";
import { useCreateVideoSnapshot } from "../../hooks/useCreateVideoSnapshot";
import { useEffect, useState } from "react";
import { useCameraSettingsContext } from "../../../../app/context/CameraSettingsContext";

type VideoFeedProps = {
  mostRecentSighting: SightingType;
  isLoading: boolean;
  size: { width: number; height: number };

  modeSetting?: number;
  isModal?: boolean;
};

const VideoFeed = ({ mostRecentSighting, isLoading, size, modeSetting, isModal = false }: VideoFeedProps) => {
  const { state: cameraSettings, dispatch } = useCameraSettingsContext();
  const contextMode = cameraSettings.mode;
  const [localMode, setLocalMode] = useState(0);
  const mode = isModal ? localMode : contextMode;
  const { image, plateRect, plateTrack } = useCreateVideoSnapshot(mostRecentSighting);

  const handleModeChange = (newMode: number) => {
    if (modeSetting) return;

    const nextMode = newMode > 2 ? 0 : newMode;

    if (isModal) {
      setLocalMode(nextMode);
    } else {
      dispatch({ type: "SET_MODE", payload: nextMode });
    }
  };

  useEffect(() => {
    const updateSize = () => {
      const width = window.innerWidth * 0.48;
      const height = (width * 2) / 3;
      dispatch({ type: "SET_IMAGE_SIZE", payload: { width, height } });
    };
    updateSize();
    window.addEventListener("resize", updateSize);
    return () => window.removeEventListener("resize", updateSize);
  }, []);

  if (isLoading) return <>Loading...</>;

  return (
    <div className="w-[70%] mt-[2%]">
      <Stage width={size.width} height={size.height} onClick={() => handleModeChange(mode + 1)}>
        <Layer>
          {image && (
            <Image
              image={image}
              height={size.height}
              width={size.width}
              onMouseEnter={(e) => {
                const container = e.target.getStage()?.container();
                if (container) container.style.cursor = "pointer";
              }}
              onMouseLeave={(e) => {
                const container = e.target.getStage()?.container();
                if (container) container.style.cursor = "default";
              }}
              cornerRadius={10}
            />
          )}
        </Layer>
        {plateRect && mode === 1 && (
          <Layer>
            <Rect
              x={plateRect?.[0] * size.width}
              y={plateRect?.[1] * size.height}
              width={plateRect?.[2] * size.width}
              height={plateRect?.[3] * size.height}
              stroke="blue"
              strokeWidth={4}
              cornerRadius={5}
            />
          </Layer>
        )}

        {plateTrack && mode === 2 && (
          <Layer>
            {plateTrack.map((rect, index) => (
              <Rect
                key={index}
                x={rect[0] * size.width}
                y={rect[1] * size.height}
                width={rect[2] * size.width}
                height={rect[3] * size.height}
                stroke="red"
                strokeWidth={2}
                cornerRadius={5}
              />
            ))}
          </Layer>
        )}
      </Stage>
    </div>
  );
};

export default VideoFeed;
