"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import jsQR from "jsqr";
import { cn } from "@/lib/utils";
import { FormField, SpinnerIcon } from "@/components/auth-form-ui";
import { useVehicleByQr } from "@/hooks/useVehicleByQr";
import {
  CloseIcon,
  ScanIcon,
  CarIcon,
  PhoneIcon,
  WhatsAppIcon,
  CheckIcon,
  QrIcon,
  AlertIcon,
} from "@/app/components/icons";

/* QR decoding is done in-browser with jsQR (a tiny, dependency-free decoder) so
   it works everywhere — the native BarcodeDetector API isn't available in
   Chrome/Firefox on Windows desktop, only on Android/ChromeOS/macOS. We grab
   frames from the camera, draw them to an offscreen canvas, and decode the
   pixels each tick. The decoded QR Code ID is then resolved to its vehicle via
   GET /vehicle/qr/:qrCodeId. */

function cameraSupported(): boolean {
  return (
    typeof navigator !== "undefined" && !!navigator.mediaDevices?.getUserMedia
  );
}

/* Pull the QR code ID out of whatever the QR encodes — either a bare ID or a
   deep link like https://vehcall.app/q/<qrCodeId>. IDs are case-sensitive, so
   (unlike a number plate) we don't upper-case the result. */
function parseQrCodeId(raw: string): string {
  const text = raw.trim();
  try {
    const url = new URL(text);
    const q =
      url.searchParams.get("qrCodeId") ||
      url.searchParams.get("qr") ||
      url.searchParams.get("q") ||
      url.searchParams.get("id");
    if (q) return q.trim();
    const seg = url.pathname.split("/").filter(Boolean).pop();
    if (seg) return decodeURIComponent(seg).trim();
  } catch {
    /* not a URL — treat the whole string as the QR code ID */
  }
  return text;
}

const capitalize = (s: string) =>
  s ? s.charAt(0).toUpperCase() + s.slice(1) : s;

type Mode = "scanning" | "manual" | "result";
type ContactMethod = "call" | "whatsapp";

// Everything the layout needs to act on a contact choice — a voice call needs
// the vehicleId (and the scanned qrCodeId, for the backend's activity log).
export interface ContactRequest {
  vehicleNumber: string;
  vehicleId: string;
  qrCodeId: string | null;
  method: ContactMethod;
}

// Decode at most this many px on the longest side — keeps jsQR fast on big frames.
const MAX_DECODE_DIM = 640;

// Mounted only while open (the parent gates it), so state is fresh on every open.
export function ScanVehicleModal({
  onClose,
  onContact,
  initialQrCodeId = null,
}: {
  onClose: () => void;
  onContact: (request: ContactRequest) => void;
  // When set (e.g. arriving via /dashboard?qr=<id>), skip the camera and resolve
  // this QR straight away — as if it had just been scanned.
  initialQrCodeId?: string | null;
}) {
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const rafRef = useRef<number | null>(null);

  const [mode, setMode] = useState<Mode>(
    initialQrCodeId ? "result" : "scanning",
  );
  const [lookupId, setLookupId] = useState<string | null>(
    initialQrCodeId ? parseQrCodeId(initialQrCodeId) : null,
  );
  const [manualValue, setManualValue] = useState("");
  // Why we dropped to manual entry (no camera / blocked camera).
  const [hint, setHint] = useState<string | null>(null);

  // Resolve the captured QR code ID to its vehicle (disabled until one is set).
  const {
    data: vehicle,
    isLoading,
    isError,
    error,
    refetch,
  } = useVehicleByQr(lookupId);

  // Tear down the camera + detection loop. Idempotent — safe to call repeatedly.
  const stopCamera = useCallback(() => {
    if (rafRef.current != null) {
      cancelAnimationFrame(rafRef.current);
      rafRef.current = null;
    }
    streamRef.current?.getTracks().forEach((t) => t.stop());
    streamRef.current = null;
  }, []);

  const handleDecoded = useCallback(
    (raw: string) => {
      stopCamera();
      setLookupId(parseQrCodeId(raw));
      setMode("result");
    },
    [stopCamera],
  );

  function close() {
    stopCamera();
    onClose();
  }

  // Escape to close + lock body scroll while mounted.
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") onClose();
    }
    document.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose]);

  // Start the camera + QR detection whenever we (re-)enter scanning mode. The
  // cleanup stops everything when we leave it (result, manual, or unmount).
  useEffect(() => {
    if (mode !== "scanning") return;
    let cancelled = false;
    let frame = 0;

    function loop() {
      if (cancelled) return;
      rafRef.current = requestAnimationFrame(loop);
      const video = videoRef.current;
      const canvas = canvasRef.current;
      if (!video || !canvas || video.readyState < 2) return;

      // Decode every other frame — plenty responsive, half the CPU.
      frame = (frame + 1) % 2;
      if (frame !== 0) return;

      const vw = video.videoWidth;
      const vh = video.videoHeight;
      if (!vw || !vh) return;

      const scale = Math.min(1, MAX_DECODE_DIM / Math.max(vw, vh));
      const cw = Math.round(vw * scale);
      const ch = Math.round(vh * scale);
      canvas.width = cw;
      canvas.height = ch;
      const ctx = canvas.getContext("2d", { willReadFrequently: true });
      if (!ctx) return;
      ctx.drawImage(video, 0, 0, cw, ch);

      const image = ctx.getImageData(0, 0, cw, ch);
      const code = jsQR(image.data, cw, ch, { inversionAttempts: "dontInvert" });
      if (code?.data) handleDecoded(code.data);
    }

    async function start() {
      if (!cameraSupported()) {
        setHint(
          "This browser can't access a camera. Enter the QR Code ID instead.",
        );
        setMode("manual");
        return;
      }
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: { ideal: "environment" } },
          audio: false,
        });
        if (cancelled) {
          stream.getTracks().forEach((t) => t.stop());
          return;
        }
        streamRef.current = stream;
        const video = videoRef.current;
        if (video) {
          video.srcObject = stream;
          await video.play().catch(() => {});
        }
        loop();
      } catch (err) {
        if (cancelled) return;
        const name = err instanceof DOMException ? err.name : "";
        setHint(
          name === "NotAllowedError"
            ? "Camera access was blocked. Allow it in your browser settings, or enter the QR Code ID below."
            : name === "NotFoundError"
              ? "No camera was found. Enter the QR Code ID below instead."
              : "Couldn't start the camera. Enter the QR Code ID below instead.",
        );
        setMode("manual");
      }
    }

    start();
    return () => {
      cancelled = true;
      stopCamera();
    };
  }, [mode, stopCamera, handleDecoded]);

  function submitManual(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const value = manualValue.trim();
    if (!value) return;
    setLookupId(parseQrCodeId(value));
    setMode("result");
  }

  function scanAgain() {
    setLookupId(null);
    setManualValue("");
    setHint(null);
    setMode("scanning");
  }

  const headerSubtitle =
    mode !== "result"
      ? "Point your camera at a VehCall QR code"
      : isLoading
        ? "Looking up vehicle…"
        : isError
          ? "Lookup failed"
          : "Vehicle identified";

  const prefs = vehicle?.contactPreferences;
  const bothPrefs = !!prefs?.call && !!prefs?.whatsapp;

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="scan-vehicle-title"
      className="fixed inset-0 z-50 flex items-end justify-center p-4 sm:items-center"
    >
      {/* Backdrop */}
      <button
        type="button"
        aria-label="Close"
        onClick={close}
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
      />

      {/* Dialog */}
      <div className="glass animate-toast-in relative max-h-[calc(100svh-2rem)] w-full max-w-md overflow-y-auto rounded-3xl">
        <div className="flex items-center justify-between gap-3 border-b border-white/8 px-6 py-5">
          <div className="flex items-center gap-3">
            <span className="grid h-10 w-10 place-items-center rounded-xl bg-brand/12 text-brand">
              <ScanIcon className="h-5 w-5" />
            </span>
            <div>
              <h2 id="scan-vehicle-title" className="text-base font-bold text-white">
                Scan Vehicle
              </h2>
              <p className="text-xs text-white/50">{headerSubtitle}</p>
            </div>
          </div>
          <button
            type="button"
            onClick={close}
            aria-label="Close"
            className="grid h-9 w-9 place-items-center rounded-lg text-white/50 transition hover:bg-white/5 hover:text-white"
          >
            <CloseIcon className="h-5 w-5" />
          </button>
        </div>

        <div className="p-6">
          {mode === "scanning" && (
            <div className="flex flex-col gap-4">
              <div className="relative aspect-square w-full overflow-hidden rounded-2xl bg-black">
                <video
                  ref={videoRef}
                  muted
                  playsInline
                  autoPlay
                  className="h-full w-full object-cover"
                />
                {/* Framing reticle */}
                <div className="pointer-events-none absolute inset-0 grid place-items-center">
                  <div className="relative h-44 w-44">
                    {[
                      "left-0 top-0 border-l-2 border-t-2 rounded-tl-xl",
                      "right-0 top-0 border-r-2 border-t-2 rounded-tr-xl",
                      "bottom-0 left-0 border-b-2 border-l-2 rounded-bl-xl",
                      "bottom-0 right-0 border-b-2 border-r-2 rounded-br-xl",
                    ].map((pos) => (
                      <span
                        key={pos}
                        className={cn("absolute h-7 w-7 border-brand", pos)}
                      />
                    ))}
                    <span className="absolute inset-x-0 top-1/2 h-px animate-pulse bg-brand/70" />
                  </div>
                </div>
              </div>
              {/* Offscreen canvas used only for pixel readback. */}
              <canvas ref={canvasRef} className="hidden" />

              <p className="text-center text-xs text-white/50">
                Hold steady — the code scans automatically.
              </p>

              <button
                type="button"
                onClick={() => {
                  stopCamera();
                  setHint(null);
                  setMode("manual");
                }}
                className="text-center text-xs font-semibold text-brand transition hover:text-brand/80"
              >
                Enter QR Code ID manually
              </button>
            </div>
          )}

          {mode === "manual" && (
            <form onSubmit={submitManual} noValidate className="flex flex-col gap-4">
              {hint && (
                <p className="rounded-xl border border-white/10 bg-white/[0.03] px-4 py-3 text-xs text-white/60">
                  {hint}
                </p>
              )}
              <FormField
                id="qrCodeId"
                label="QR Code ID"
                type="text"
                placeholder="Paste or type the QR code ID"
                value={manualValue}
                onChange={(v) => setManualValue(v)}
              />
              <button
                type="submit"
                disabled={!manualValue.trim()}
                className="btn-primary w-full text-sm disabled:cursor-not-allowed disabled:opacity-60"
              >
                <QrIcon className="h-4 w-4" />
                Find vehicle
              </button>
              {cameraSupported() && (
                <button
                  type="button"
                  onClick={scanAgain}
                  className="text-center text-xs font-semibold text-brand transition hover:text-brand/80"
                >
                  Use the camera instead
                </button>
              )}
            </form>
          )}

          {mode === "result" && (
            <div className="flex flex-col gap-5">
              {isLoading && (
                <div className="flex flex-col items-center gap-3 py-6 text-center">
                  <span className="text-brand">
                    <SpinnerIcon />
                  </span>
                  <p className="text-sm text-white/60">Looking up vehicle…</p>
                  {lookupId && (
                    <p className="break-all text-[11px] text-white/35">
                      QR · {lookupId}
                    </p>
                  )}
                </div>
              )}

              {isError && (
                <div className="flex flex-col items-center gap-4 text-center">
                  <span className="grid h-14 w-14 place-items-center rounded-full bg-danger/15 text-danger">
                    <AlertIcon className="h-7 w-7" />
                  </span>
                  <div>
                    <p className="text-sm font-semibold text-white">
                      {error?.code === 404
                        ? "No vehicle linked to this QR"
                        : "Couldn't look up this QR"}
                    </p>
                    <p className="mt-1 text-xs text-white/50">
                      {error?.code === 404
                        ? "Double-check the QR Code ID, or try scanning again."
                        : (error?.message ??
                          "Check your connection and try again.")}
                    </p>
                    {lookupId && (
                      <p className="mt-2 break-all text-[11px] text-white/35">
                        QR · {lookupId}
                      </p>
                    )}
                  </div>
                  <div className="flex w-full gap-3">
                    {error?.code !== 404 && (
                      <button
                        type="button"
                        onClick={() => refetch()}
                        className="btn-primary flex-1 text-sm"
                      >
                        Retry
                      </button>
                    )}
                    <button
                      type="button"
                      onClick={scanAgain}
                      className="btn-ghost flex-1 text-sm"
                    >
                      Scan again
                    </button>
                  </div>
                </div>
              )}

              {vehicle && !isLoading && !isError && (
                <>
                  <div className="flex flex-col items-center gap-3 text-center">
                    <span className="grid h-14 w-14 place-items-center rounded-full bg-success/15 text-success">
                      <CheckIcon className="h-7 w-7" />
                    </span>
                    <div className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/[0.03] px-4 py-2.5">
                      <CarIcon className="h-5 w-5 text-brand" />
                      <span className="text-lg font-bold tracking-wide text-white">
                        {vehicle.vehicleNumber}
                      </span>
                    </div>
                    <p className="text-xs text-white/55">
                      {[vehicle.brand, vehicle.model].filter(Boolean).join(" ")}
                      {vehicle.type ? ` · ${capitalize(vehicle.type)}` : ""}
                    </p>
                    <p className="max-w-xs text-xs text-white/45">
                      Your number stays private — VehCall connects you with the
                      owner without sharing either side&apos;s details.
                    </p>
                  </div>

                  {prefs?.call || prefs?.whatsapp ? (
                    <div
                      className={cn(
                        "grid gap-3",
                        bothPrefs ? "grid-cols-2" : "grid-cols-1",
                      )}
                    >
                      {prefs?.call && (
                        <button
                          type="button"
                          onClick={() =>
                            onContact({
                              vehicleNumber: vehicle.vehicleNumber,
                              vehicleId: vehicle.vehicleId,
                              qrCodeId: lookupId,
                              method: "call",
                            })
                          }
                          className="btn-primary text-sm"
                        >
                          <PhoneIcon className="h-4 w-4" />
                          Request call
                        </button>
                      )}
                      {prefs?.whatsapp && (
                        <button
                          type="button"
                          onClick={() =>
                            onContact({
                              vehicleNumber: vehicle.vehicleNumber,
                              vehicleId: vehicle.vehicleId,
                              qrCodeId: lookupId,
                              method: "whatsapp",
                            })
                          }
                          className="flex items-center justify-center gap-2 rounded-xl bg-success/15 px-4 py-3 text-sm font-semibold text-success transition hover:bg-success/25"
                        >
                          <WhatsAppIcon className="h-4 w-4" />
                          WhatsApp
                        </button>
                      )}
                    </div>
                  ) : (
                    <p className="rounded-xl border border-white/10 bg-white/[0.03] px-4 py-3 text-center text-xs text-white/50">
                      The owner hasn&apos;t enabled direct contact for this
                      vehicle.
                    </p>
                  )}

                  <button
                    type="button"
                    onClick={scanAgain}
                    className="btn-ghost w-full text-sm"
                  >
                    <ScanIcon className="h-4 w-4" />
                    Scan another vehicle
                  </button>
                </>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
