import { useGetOverviewSnapshot } from "../../hooks/useGetOverviewSnapshot";
import type { ZoomInOptions } from "../../types/types";
import NavigationArrow from "../UI/NavigationArrow";
import { useCameraZoom } from "../../hooks/useCameraZoom";
import { useEffect } from "react";
import Loading from "../UI/Loading";
import ErrorState from "../UI/ErrorState";

type SnapshotContainerProps = {
  side: string;
  settingsPage?: boolean;
  zoomLevel?: number;
  onZoomLevelChange?: (level: number) => void;
};

export const SnapshotContainer = ({
  side,
  settingsPage,
  zoomLevel,
  onZoomLevelChange,
}: SnapshotContainerProps) => {
  const { canvasRef, isError, isPending } = useGetOverviewSnapshot(side);
  const cameraControllerSide =
    side === "CameraA" ? "CameraControllerA" : "CameraControllerB";
  const { mutation } = useCameraZoom({ camera: cameraControllerSide });

  const handleZoomClick = () => {
    const baseLevel = zoomLevel ?? 1;
    const newLevel = baseLevel >= 8 ? 1 : baseLevel * 2;

    if (onZoomLevelChange) onZoomLevelChange(newLevel);

    if (!zoomLevel) return;
  };

  useEffect(() => {
    if (zoomLevel) {
      const zoomInOptions: ZoomInOptions = {
        camera: cameraControllerSide,
        multiplier: zoomLevel,
      };
      mutation.mutate(zoomInOptions);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [zoomLevel]);

  return (
    <div className="flex flex-col md:flex-row">
      <NavigationArrow side={side} settingsPage={settingsPage} />
      <div className="w-full">
        {isError && <ErrorState />}
        {isPending && (
          <div className="my-50 h-[50%]">
            <Loading message="Camera Preview" />
          </div>
        )}
        <canvas
          onClick={handleZoomClick}
          ref={canvasRef}
          className="absolute inset-0 object-contain min-h-[100%] z-20"
        />
      </div>
    </div>
  );
};
