"use client";

import { useEffect, useRef, useState } from "react";
import { Html5Qrcode } from "html5-qrcode";
import { motion, AnimatePresence } from "framer-motion";
import { useRouter, useParams } from "next/navigation";

import { useSession } from "next-auth/react";
import Loading from "../../../components/Loading";

export default function ScanPage() {
  const scannerRef = useRef<Html5Qrcode | null>(null);
  const router = useRouter();
  const params = useParams();
  const successSoundRef = useRef<HTMLAudioElement | null>(null);

  const { data: session, status } = useSession();
  const currentUser = session?.user as any;

  const location_id = params.location_id as string;

  const [locationName, setLocationName] = useState("");
  const [scanned, setScanned] = useState("");
  const [item, setItem] = useState<any>(null);
  const [quantity, setQuantity] = useState<number>(1);

  const [loading, setLoading] = useState(false);
  const [isPaused, setIsPaused] = useState(false);

  const lastScanRef = useRef<number>(0);
  const processingRef = useRef(false);

  /* ================= NORMALIZE ================= */
  const normalize = (text: string) => {
    return text
      .toString()
      .trim()
      .replace(/\s+/g, "")
      .replace(/^0+/, "")
      .toUpperCase();
  };

  /* ================= FETCH LOCATION ================= */
  useEffect(() => {
    if (status === "loading") return;

    if (status === "unauthenticated") {
      router.replace("/login");
      return;
    }
    const allowedRoles = ["ADMIN"];

    if (!allowedRoles.includes(currentUser?.role)) {
      router.replace("/inventory");
      return;
    }


    const fetchLocation = async () => {
      try {
        const res = await fetch(`/api/gudang/scan/${location_id}`, {
          cache: "no-store",
        });

        if (!res.ok) {
          setLocationName("Gudang tidak ditemukan");
          return;
        }

        const json = await res.json();
        setLocationName(json.location?.name || "Gudang");
      } catch {
        setLocationName("Error load gudang");
      }
    };

    if (location_id) fetchLocation();
  }, [location_id, status, router]);

  /* ================= SCANNER ================= */
  useEffect(() => {
    let scanner: Html5Qrcode | null = null;

    const startScanner = async () => {
      const readerElement = document.getElementById("reader");

      // 🔥 FIX: DOM safety check
      if (!readerElement) {
        setTimeout(startScanner, 300);
        return;
      }

      scanner = new Html5Qrcode("reader");
      scannerRef.current = scanner;

      const config = {
        fps: 12,
        qrbox: (w: number, h: number) => {
          const size = Math.min(w, h) * 0.75;
          return { width: size, height: size };
        },
      };

      try {
        await scanner.start(
          { facingMode: "environment" },
          config,
          async (decodedText: string) => {
            const now = Date.now();

            if (processingRef.current) return;
            if (now - lastScanRef.current < 800) return;

            processingRef.current = true;
            lastScanRef.current = now;

            const clean = normalize(decodedText);
            setScanned(clean);

            setIsPaused(true);
            await scanner?.pause(true);

            try {
              new Audio("/beep.mp3").play();
            } catch {}

            setLoading(true);

            try {
              const res = await fetch(
                `/api/items/scan/${encodeURIComponent(clean)}`,
                { cache: "no-store" }
              );

              const json = await res.json();
              successSoundRef.current?.play().catch(() => {});
              setItem(json.item || null);
            } catch {
              setItem(null);
            }

            setLoading(false);

            setTimeout(() => {
              processingRef.current = false;
            }, 500);
          },
          () => {}
        );
      } catch (err) {
        console.error("Camera start error:", err);
      }
    };

    startScanner();

    return () => {
      scanner?.stop().catch(() => {});
    };
  }, []);

  useEffect(() => {
    successSoundRef.current = new Audio("/sound/click.wav");
    successSoundRef.current.preload = "auto";
  }, []);
  /* ================= RESET ================= */
  const handleScanAgain = async () => {
    setScanned("");
    setItem(null);
    setQuantity(1);
    setLoading(false);

    processingRef.current = false;
    lastScanRef.current = 0;

    await scannerRef.current?.resume();
    setIsPaused(false);
  };

  /* ================= SAVE (FIX: CREATED_BY ADDED) ================= */
  const handleSave = async () => {
    if (!item) return;

    try {
      setLoading(true);

      const res = await fetch("/api/inventory", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          item_id: item.id,
          location_id: Number(location_id),
          quantity: Number(quantity),

          // 🔥 FIX: ADD CREATED BY FROM SESSION
          created_by: currentUser?.id || null,
        }),
      });

      if (!res.ok) throw new Error();

      alert("Stok berhasil ditambahkan 🌱");

      handleScanAgain();
    } catch {
      alert("Gagal simpan");
    } finally {
      setLoading(false);
    }
  };

  if (!session) return null;

  return (
    <div className="min-h-screen bg-linear-to-b from-green-50 via-emerald-50 to-lime-50 p-4 space-y-5">

      {/* ================= HEADER ================= */}
      <div className="rounded-3xl p-5 bg-white/80 backdrop-blur-xl border border-green-100 shadow-xl">

        <div className="flex items-center justify-between">
          <h1 className="text-lg md:text-xl font-bold text-green-900">
            📷 Scan - {locationName}
          </h1>

          <div className="flex gap-2">
            <button
              onClick={handleScanAgain}
              className="px-4 py-2 text-sm rounded-xl bg-white border shadow hover:scale-105"
            >
              Scan Lagi
            </button>

            <button
              onClick={() => router.push("/inventory")}
              className="px-4 py-2 text-sm rounded-xl bg-green-600 text-white shadow hover:scale-105"
            >
              Kembali
            </button>
          </div>
        </div>

        <p className="text-sm text-green-700 mt-2">
          {isPaused
            ? "⏸ Paused - isi quantity"
            : "Arahkan barcode ke kamera"}
        </p>
      </div>

      {/* ================= CAMERA ================= */}
      <div className="relative rounded-3xl overflow-hidden border shadow-xl bg-black">
        <div id="reader" className="w-full h-75" />

        <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
          <div className="w-[75%] aspect-square border-2 border-green-400 rounded-2xl shadow-[0_0_30px_rgba(34,197,94,0.6)] animate-pulse" />
        </div>
      </div>

      {/* ================= POPUP ================= */}
      <AnimatePresence>
        {isPaused && (
          <motion.div
            className="fixed inset-0 z-50 flex items-end md:items-center justify-center bg-black/40 backdrop-blur-sm"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
          >
            <motion.div
              initial={{ y: 120 }}
              animate={{ y: 0 }}
              exit={{ y: 120 }}
              className="w-full md:max-w-md p-5 rounded-t-3xl md:rounded-3xl
              bg-white/80 backdrop-blur-2xl
              border border-green-100
              shadow-[0_30px_80px_rgba(0,0,0,0.25)]
              space-y-4"
            >

              <div className="text-xs bg-green-50 p-2 rounded-xl text-center break-all">
                {scanned}
              </div>

              {loading && (
                <div className="text-sm text-green-700 animate-pulse">
                  🔍 Mencari item...
                </div>
              )}

              {item && !loading && (
                <>
                  <div className="p-4 rounded-2xl bg-linear-to-br from-green-100 via-white to-lime-100 border shadow">
                    <div className="font-bold text-green-900">
                      🌾 {item.name}
                    </div>
                    <div className="text-sm text-gray-600">
                      SKU: {item.sku}
                    </div>
                    <div className="text-sm text-gray-600">
                      Unit: {item.unit}
                    </div>
                  </div>

                  <input
                    type="number"
                    value={quantity}
                    onChange={(e) =>
                      setQuantity(Number(e.target.value))
                    }
                    className="w-full px-4 py-3 rounded-xl border shadow-inner"
                  />

                  <button
                    onClick={handleSave}
                    className="w-full py-3 rounded-xl bg-green-600 text-white font-semibold shadow-lg hover:scale-105"
                  >
                    Simpan Stok 🌱
                  </button>
                </>
              )}

              {!item && !loading && (
                <div className="text-sm text-red-500 text-center">
                  Item tidak ditemukan
                </div>
              )}

              <button
                onClick={handleScanAgain}
                className="w-full py-2 rounded-xl bg-white border shadow"
              >
                Scan Lagi
              </button>

            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

    </div>
  );
}