import { useCallback, useRef, useState } from "react";
import { BLANK_IMG } from "../../utils/utils";
import { useOverviewOverlay } from "../../hooks/useOverviewOverlay";
import { useSightingFeedContext } from "../../context/SightingFeedContext";
import { useHiDPICanvas } from "../../hooks/useHiDPICanvas";
import NavigationArrow from "../UI/NavigationArrow";
import NumberPlate from "../PlateStack/NumberPlate";
import Loading from "../UI/Loading";

const SightingOverview = () => {
  const [overlayMode, setOverlayMode] = useState<0 | 1 | 2>(0);

  const imgRef = useRef<HTMLImageElement | null>(null);
  const canvasRef = useRef<HTMLCanvasElement | null>(null);

  const onOverviewClick = useCallback(() => {
    setOverlayMode((m) => ((m + 1) % 3) as 0 | 1 | 2);
  }, []);

  const { side, mostRecent, isError, isLoading } = useSightingFeedContext();

  useOverviewOverlay(mostRecent, overlayMode, imgRef, canvasRef);

  const { sync } = useHiDPICanvas(imgRef, canvasRef);

  if (isLoading)
    return (
      <div className="h-150 flex items-center justify-center">
        <NavigationArrow side={side} />
        <Loading message="Loading" />
      </div>
    );

  if (isError) return;
  <div className="h-100 flex items-center justify-center text-red-500 text-lg">
    An error occurred. Cannot display footage.
  </div>;

  if (!mostRecent)
    return (
      <div className="h-150 flex items-center justify-center text-3xl animate-pulse">
        <NavigationArrow side={side} />
        <Loading message="No Recent Sightings" />
      </div>
    );

  return (
    <div className="flex flex-col md:flex-row">
      <NavigationArrow side={side} />

      <div className="w-full">
        {mostRecent && (
          <div className="absolute inset-0 z-50 px-1 pt-2">
            <NumberPlate vrm={mostRecent?.vrm} size="sm" />
          </div>
        )}
        <img
          ref={imgRef}
          onLoad={() => {
            sync();
            setOverlayMode((m) => m);
          }}
          src={mostRecent?.overviewUrl || BLANK_IMG}
          alt="overview"
          className="absolute inset-0 object-contain cursor-pointer z-10 min-h-[100%] rounded-lg"
          onClick={onOverviewClick}
          style={{
            display: mostRecent?.overviewUrl ? "block" : "none",
          }}
        />
        <canvas
          ref={canvasRef}
          className="absolute inset-0 object-contain z-20 pointer-events-none "
        />
      </div>
    </div>
  );
};

export default SightingOverview;
