"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import jsQR from "jsqr";
import { useLatest } from "@/hooks/useLatest";

/**
 * A live QR scan from the device camera, with a still-image fallback.
 *
 * Extracted from `SelfScanModal` because it is all lifecycle and no markup, and
 * because three things about it are easy to break:
 *
 *  - **`submittingRef`** stops jsQR firing a second time while the first submit
 *    is in flight. The scan loop runs every animation frame, so without it one
 *    sheet held up for a second sends the same code a dozen times.
 *  - **`cancelled`** is checked after every `await`. The dialog can close while
 *    `getUserMedia` is still resolving, and the stream then has to be stopped
 *    rather than left running against an unmounted video element.
 *  - **re-arming on failure** keeps the camera up after a rejected code, so the
 *    participant can point at the other sheet without reopening the dialog.
 */
export function useQrScanner({
  open,
  onScan,
  onClose,
  t,
}: {
  open: boolean;
  /** Rejects to mean "not accepted" — the caller has already said why. */
  onScan: (code: string) => Promise<void>;
  onClose: () => void;
  t: (key: string) => string;
}) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const animationRef = useRef<number | null>(null);
  /** Guards against jsQR firing again while the first submit is in flight. */
  const submittingRef = useRef(false);

  const [cameraError, setCameraError] = useState<string | null>(null);
  const [scanning, setScanning] = useState(false);
  /**
   * Bumped after a rejected code. `submit` stops the camera before sending, so
   * re-arming means starting it again; flipping `scanning` alone left a black
   * preview captioned "point the camera" until the dialog was reopened.
   */
  const [armCount, setArmCount] = useState(0);

  const stopCamera = useCallback(() => {
    if (animationRef.current) {
      cancelAnimationFrame(animationRef.current);
      animationRef.current = null;
    }
    streamRef.current?.getTracks().forEach((track) => track.stop());
    streamRef.current = null;
    if (videoRef.current) videoRef.current.srcObject = null;
    setScanning(false);
  }, []);

  const submit = useCallback(
    async (code: string) => {
      if (submittingRef.current) return;
      submittingRef.current = true;
      stopCamera();
      try {
        await onScan(code);
        onClose();
      } catch {
        // The caller has already surfaced the reason; re-arm so the participant
        // can point at the other sheet without reopening the dialog.
        submittingRef.current = false;
        setArmCount((count) => count + 1);
      }
    },
    [onClose, onScan, stopCamera]
  );

  // Decode a still image — the fallback when there is no usable camera.
  const decodeFile = (file: File) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      const image = new window.Image();
      image.onload = () => {
        const canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        const context = canvas.getContext("2d");
        if (!context) return;
        context.drawImage(image, 0, 0);
        const { data, width, height } = context.getImageData(
          0,
          0,
          image.width,
          image.height
        );
        const found = jsQR(data, width, height);
        if (found) {
          submit(found.data);
        } else {
          setCameraError(t("COMMON.NO_QR_FOUNDED"));
        }
      };
      image.src = event.target?.result as string;
    };
    reader.readAsDataURL(file);
  };

  /*
   * Clear any previous failure as the dialog opens, so reopening it does not
   * start on "camera unavailable" from last time.
   *
   * React's adjust-on-change pattern rather than the first line of the effect
   * below: the error is genuine state — the camera handler and the file decoder
   * both set it asynchronously — but *resetting* it is a reaction to `open`
   * changing, and doing it in the effect meant the dialog painted one frame
   * with the stale error still showing.
   */
  const [openedWith, setOpenedWith] = useState(open);
  if (open !== openedWith) {
    setOpenedWith(open);
    setCameraError(null);
  }

  /* The current `submit`, for the frame loop below — see the note on that
     effect's dependency list. */
  const latestSubmit = useLatest(submit);

  useEffect(() => {
    if (!open) return;

    let cancelled = false;
    submittingRef.current = false;

    const tick = () => {
      if (cancelled) return;
      const video = videoRef.current;
      const canvas = canvasRef.current;
      if (video && canvas && video.readyState === video.HAVE_ENOUGH_DATA) {
        const context = canvas.getContext("2d", { willReadFrequently: true });
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context?.drawImage(video, 0, 0, canvas.width, canvas.height);
        const imageData = context?.getImageData(0, 0, canvas.width, canvas.height);
        if (imageData) {
          try {
            const found = jsQR(imageData.data, imageData.width, imageData.height);
            if (found) {
              latestSubmit.current(found.data);
              return;
            }
          } catch (error) {
            console.error("QR scanning error:", error);
          }
        }
      }
      animationRef.current = requestAnimationFrame(tick);
    };

    const start = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: "environment" },
        });
        if (cancelled) {
          stream.getTracks().forEach((track) => track.stop());
          return;
        }
        streamRef.current = stream;
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
          await videoRef.current.play();
        }
        setScanning(true);
        tick();
      } catch (error) {
        console.error("Camera unavailable:", error);
        if (!cancelled) setCameraError(t("COMMON.CAMERA_UNAVAILABLE"));
      }
    };

    start();

    return () => {
      cancelled = true;
      stopCamera();
    };
    /*
     * `submit` goes through `latestSubmit` rather than the dependency list.
     *
     * It is not stable: it depends on `onScan` and `onClose`, which are the
     * caller's props — a call site passing inline arrows gives it a new
     * identity every render, and listing it would then tear down the camera
     * and re-acquire it on every render, mid-scan. The ref means the loop
     * always calls the current one without the effect restarting, which is
     * also the correct read: `tick` fires frame after frame, long after this
     * render's closure was built. See `useLatest`.
     *
     * `stopCamera` and `t` *are* listed. `stopCamera` has an empty dependency
     * list of its own so it never changes identity, and `t` changes only when
     * the language does — on which this camera *should* restart, because the
     * error message it would show is the one being re-translated.
     */
  }, [open, armCount, stopCamera, t, latestSubmit]);

  return { videoRef, canvasRef, cameraError, scanning, decodeFile, stopCamera };
}
