import { Stage, Layer, Image } from "react-konva";
import { useCreateVideoPreviewSnapshot } from "../../hooks/useCreatePreviewImage";
import { useEffect, type RefObject } from "react";
import { useCameraSettingsContext } from "../../../../app/context/CameraSettingsContext";

const VideoFeedSetup = () => {
  const { latestBitmapRef, isLoading } = useCreateVideoPreviewSnapshot();
  const { state, dispatch } = useCameraSettingsContext();
  const size = state.imageSize;

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

  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="mt-[1%]">
      <Stage width={size.width} height={size.height}>
        <Layer>{image && <Image image={image} height={size.height} width={size.width} cornerRadius={10} />}</Layer>
      </Stage>
    </div>
  );
};

export default VideoFeedSetup;
