import { useGetOverviewSnapshot } from "../../hooks/useGetOverviewSnapshot";
import type { ZoomLevel } from "../../types/types";
import NavigationArrow from "../UI/NavigationArrow";

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

export const SnapshotContainer = ({
  side,
  settingsPage,
  zoomLevel,
  onZoomLevelChange,
}: SnapshotContainerProps) => {
  const { canvasRef, isError, isPending } = useGetOverviewSnapshot();
  if (isError) return <p className="h-100">An error occurred</p>;
  if (isPending) return <p className="h-100">Loading...</p>;

  const handleZoomClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
    const bounds = canvasRef.current?.getBoundingClientRect();
    if (!bounds) return;
    const left = bounds.left;
    const top = bounds.top;
    const x = event.pageX;
    const y = event.pageY;
    const cw = canvasRef.current?.clientWidth;
    const ch = canvasRef.current?.clientHeight;
    if (!cw || !ch) return;
    const px = x / cw;
    const py = y / ch;

    const baseLevel = zoomLevel?.level ?? 1;
    const newLevel = baseLevel >= 8 ? 1 : baseLevel * 2;

    if (onZoomLevelChange)
      onZoomLevelChange({
        left,
        top,
        x,
        y,
        px,
        py,
        level: newLevel,
      });
  };

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