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

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 { effectiveSelected } = useSightingFeedContext();

  useOverviewOverlay(effectiveSelected, overlayMode, imgRef, canvasRef);

  const { sync } = useHiDPICanvas(imgRef, canvasRef);
  return (
    <div className="mt-2 grid gap-3">
      {/* <div className="flex items-center gap-3 text-sm">
        <div className="font-semibold">{effectiveSelected?.vrm ?? "—"}</div>
        <div>{effectiveSelected?.countryCode ?? "—"}</div>
        <div className="opacity-80">{effectiveSelected?.timeStamp ?? "—"}</div>
      </div> */}

      <div className="inline-block">
        <div className="relative aspect-[5/4]">
          <img
            ref={imgRef}
            onLoad={() => {
              sync();
              setOverlayMode((m) => m);
            }}
            src={effectiveSelected?.overviewUrl || BLANK_IMG}
            alt="overview"
            className="absolute inset-0 w-full h-full object-contain cursor-pointer z-10"
            onClick={onOverviewClick}
            style={{
              display: effectiveSelected?.overviewUrl ? "block" : "none",
            }}
          />
          <canvas
            ref={canvasRef}
            className="absolute inset-0 w-full h-full object-contain z-20 pointer-events-none"
          />
        </div>
      </div>

      <SightingWidgetDetails effectiveSelected={effectiveSelected} />

      <div className="text-xs opacity-80">
        Overlay:{" "}
        {overlayMode === 0
          ? "Off"
          : overlayMode === 1
          ? "Plate box"
          : "Track + box"}{" "}
        (click image to toggle)
      </div>
    </div>
  );
};

export default SightingOverview;
