"use client";

import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Select3D } from "../components/Select3D";
import { InventoryTable } from "./InventoryTable";

import { useSession } from "next-auth/react";
import Loading from "../components/Loading";
import { useRouter } from "next/navigation"; 
import { Printer, QrCode } from "lucide-react";
import { formatNumber } from "../components/formatNumber";
/* ================= TYPES ================= */
type Inventory = {
  item_id: number;
  sku: string;
  name: string;
  category: string;
  unit: string;

  location_id: number;
  location_name: string;
  
  quantity: number;
  reserved_quantity: number;
  barcode?: string | null; // tambah ini
};

type LocationOption = {
  id: number;
  name: string;
};

/* ================= PAGE ================= */
export default function InventoryPage() {
  const [datas, setDatas] = useState<Inventory[]>([]);
  const [locations, setLocations] = useState<LocationOption[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedItems, setSelectedItems] = useState<string[]>([]);

  const { data: session, status } = useSession();
  const router = useRouter();
  const currentUser = session?.user as any;
    
  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");

  const [locationId, setLocationId] = useState("");

  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);

  const [total, setTotal] = useState(0);
  const [totalQty, setTotalQty] = useState(0);

  // 🔥 MODAL STATE
  const [showAddOption, setShowAddOption] = useState(false);

  // 🔥 NEW: SELECT LOCATION BEFORE SCAN
  const [showSelectLocation, setShowSelectLocation] = useState(false);
  const [selectedScanLocation, setSelectedScanLocation] = useState("");

  const toggleSelectItem = (key: string) => {
    setSelectedItems((prev) =>
      prev.includes(key)
        ? prev.filter((x) => x !== key)
        : [...prev, key]
    );
  };

  const selectAllCurrentPage = () => {
    setSelectedItems(
      datas.map((x) => `${x.item_id}-${x.location_id}`)
    );
  };

  const clearSelection = () => {
    setSelectedItems([]);
  };


// 5. FUNCTION PRINT QR, single / selected / all

  const handlePrintQr = (
        type: "single" | "selected" | "all",
        row?: Inventory
      ): void => {
        let items: Inventory[] = [];

        if (type === "single" && row) {
          items = [row];
        }

        if (type === "selected") {
          items = datas.filter((x) =>
            selectedItems.includes(`${x.item_id}-${x.location_id}`)
          );
        }

        if (type === "all") {
          items = datas;
        }

        items = items.filter((x) => x.barcode);

        if (items.length === 0) {
          alert("Tidak ada barcode untuk diprint");
          return;
        }

        const win = window.open("", "_blank", "width=1000,height=800");
        if (!win) return;

        const html = items
          .map(
            (item) => `
            <div class="card">
              <div class="name">${item.name}</div>
              <div class="sku">${item.sku}</div>

              <img src="https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(
                item.barcode || ""
              )}" />

              <div class="code">${item.barcode}</div>
            </div>
          `
          )
          .join("");

        win.document.write(`
          <html>
            <head>
              <title>Print QR Code</title>

              <style>
                @page{
                  size:A4 portrait;
                  margin:8mm;
                }

                body{
                  margin:0;
                  padding:10px;
                  font-family:Arial, sans-serif;
                  background:#fff;
                }

                .toolbar{
                  margin-bottom:12px;
                }

                button{
                  padding:8px 14px;
                  border:none;
                  border-radius:8px;
                  margin-right:8px;
                  cursor:pointer;
                  font-weight:600;
                }

                .print{background:#16a34a;color:white;}
                .close{background:#e5e7eb;}

                .grid{
                  display:grid;
                  grid-template-columns:repeat(4,1fr);
                  gap:10px;
                }

                .card{
                  border:1px solid #ddd;
                  border-radius:8px;
                  padding:8px;
                  text-align:center;
                  break-inside:avoid;
                  page-break-inside:avoid;
                }

                .name{
                  font-size:11px;
                  font-weight:700;
                  min-height:28px;
                  line-height:1.2;
                  overflow:hidden;
                }

                .sku{
                  font-size:10px;
                  color:#666;
                  margin-top:2px;
                }

                img{
                  width:120px;
                  height:120px;
                  display:block;
                  margin:6px auto;
                }

                .code{
                  font-size:10px;
                  word-break:break-all;
                  line-height:1.2;
                }

                @media print{
                  .toolbar{display:none;}
                  body{padding:0;}
                }
              </style>
            </head>

            <body>
              <div class="toolbar">
                <button class="print" onclick="window.print()">Print</button>
                <button class="close" onclick="window.close()">Close</button>
              </div>

              <div class="grid">
                ${html}
              </div>
            </body>
          </html>
        `);

        win.document.close();
      };
  /* ================= DEBOUNCE ================= */
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(search.trim());
    }, 400);

    return () => clearTimeout(timer);
  }, [search]);

  /* ================= RESET PAGE ================= */
  useEffect(() => {
    setPage(1);
  }, [debouncedSearch, locationId, limit]);

  /* ================= FETCH ================= */
  useEffect(() => {
    // 1. tunggu session selesai load
    if (status === "loading") return;

    // 2. kalau belum login
    if (status === "unauthenticated") {
      router.replace("/login");
      return;
    }

      const allowedRoles = ["ADMIN", "OPERATOR", "SUPERVISOR"];

      if (!allowedRoles.includes(currentUser?.role)) {
        router.replace("/inventory");
        return;
      }


    const fetchData = async () => {
      setLoading(true);

      const res = await fetch(
        `/api/inventory?search=${encodeURIComponent(
          debouncedSearch
        )}&location_id=${locationId}&page=${page}&limit=${limit}`,
        { cache: "no-store" }
      );

      const json = await res.json();

      setDatas(json.data || []);
      setTotal(json.total || 0);
      setTotalQty(Number(json.total_quantity || 0));

      setLoading(false);
    };

    fetchData();
  }, [debouncedSearch, locationId, page, limit, status]);

  /* ================= FETCH LOCATIONS ================= */
  useEffect(() => {
    const fetchLocations = async () => {
      const res = await fetch("/api/gudang");
      const json = await res.json();
      setLocations(json.locations || []);
    };

    fetchLocations();
  }, []);

  const totalPage = Math.max(1, Math.ceil(total / limit));
   // optional safety (biar tidak flash UI)
    // if (!session) return null;

    if (status === "loading") {
      return <Loading />;
    }

    if (status === "unauthenticated") {
      return null;
    }
    
  return (
    <div className="space-y-6 p-4">

      {/* ================= HEADER ================= */}
     <motion.div
        initial={{ opacity: 0, y: 20, scale: 0.98 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        className="relative overflow-hidden rounded-3xl"
      >
        {/* BACKGROUND */}
        <div className="absolute inset-0 bg-linear-to-br from-green-300 via-emerald-200 to-lime-200" />
        <div className="absolute inset-0 bg-white/35 backdrop-blur-2xl" />

        {/* CONTENT */}
        <div
          className="
          relative z-10
          rounded-3xl
          border border-white/50
          bg-white/65
          backdrop-blur-2xl
          shadow-xl shadow-green-100/40
          p-4 sm:p-5 md:p-6
        "
        >
          <div className="flex flex-col xl:flex-row xl:items-start xl:justify-between gap-5">

            {/* LEFT */}
            <div className="min-w-0">
              <h1
                className="
                text-2xl sm:text-3xl md:text-4xl
                font-bold tracking-tight
                text-green-900
                leading-tight
              "
              >
                🌾 Stok Pergudang
              </h1>

              <div
                className="
                mt-3
                grid grid-cols-1 sm:grid-cols-2
                gap-2 sm:gap-3
                text-sm
              "
              >
                <div className="rounded-xl bg-white/70 border border-white/60 px-4 py-2 shadow-sm">
                  <span className="text-green-900/70">Total Data</span>
                  <div className="font-bold text-green-900 text-base">
                    {formatNumber(total)}
                  </div>
                </div>

                <div className="rounded-xl bg-white/70 border border-white/60 px-4 py-2 shadow-sm">
                  <span className="text-green-900/70">Total Stock</span>
                  <div className="font-bold text-green-700 text-base">
                    {formatNumber(totalQty)}
                  </div>
                </div>
              </div>
            </div>

            {/* RIGHT */}
            <div className="w-full xl:w-auto space-y-3">

              {/* FILTER */}
              <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-2">

                <div className="sm:col-span-2 xl:col-span-1 min-w-0">
                  <Input
                    value={search}
                    onChange={setSearch}
                    placeholder="Cari SKU / nama barang..."
                  />
                </div>

                <div className="min-w-0">
                  <Select3D
                    value={locationId}
                    onChange={setLocationId}
                    placeholder="Semua Gudang"
                    options={[
                      { label: "Semua Gudang", value: "" },
                      ...locations.map((l) => ({
                        label: l.name,
                        value: l.id,
                      })),
                    ]}
                  />
                </div>

                <div className="min-w-0">
                  <Select3D
                    value={String(limit)}
                    onChange={(val: string) => setLimit(Number(val))}
                    options={[
                      { label: "10", value: "10" },
                      { label: "20", value: "20" },
                      { label: "50", value: "50" },
                      { label: "100", value: "100" },
                    ]}
                  />
                </div>
              </div>

              {/* ACTION BUTTONS */}
              <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-5 gap-2">

                {/* Tambah */}
                <button
                  onClick={() => setShowAddOption(true)}
                  className="
                  col-span-2 sm:col-span-3 xl:col-span-1
                  h-11 px-4 rounded-xl
                  flex items-center justify-center gap-2
                  bg-linear-to-r from-emerald-600 to-green-500
                  text-white text-sm font-semibold
                  shadow-lg shadow-green-200/50
                  hover:scale-[1.02]
                  active:scale-95
                  transition-all
                "
                >
                  <span className="text-lg leading-none">＋</span>
                  Tambah Inventory
                </button>

                {/* Pilih Semua */}
                <button
                  onClick={selectAllCurrentPage}
                  className="
                  h-11 px-4 rounded-xl
                  bg-white/85 border border-green-100
                  text-sm font-medium text-green-900
                  shadow-sm hover:bg-white
                  active:scale-95 transition
                "
                >
                  Pilih Semua
                </button>

                {/* Clear */}
                <button
                  onClick={clearSelection}
                  className="
                  h-11 px-4 rounded-xl
                  bg-white/85 border border-red-100
                  text-sm font-medium text-red-600
                  shadow-sm hover:bg-white
                  active:scale-95 transition
                "
                >
                  Clear
                </button>

                {/* Print Pilihan */}
                <button
                  onClick={() => handlePrintQr("selected")}
                  className="
                  h-11 px-4 rounded-xl
                  flex items-center justify-center gap-2
                  bg-linear-to-r from-indigo-600 to-blue-500
                  text-white text-sm font-medium
                  shadow-md hover:scale-[1.02]
                  active:scale-95 transition
                "
                >
                  <Printer className="w-4 h-4" />
                  <span className="hidden sm:inline">Print Pilihan</span>
                  <span className="sm:hidden">Pilihan</span>
                </button>

                {/* Print Semua */}
                <button
                  onClick={() => handlePrintQr("all")}
                  className="
                  h-11 px-4 rounded-xl
                  flex items-center justify-center gap-2
                  bg-linear-to-r from-slate-700 to-slate-600
                  text-white text-sm font-medium
                  shadow-md hover:scale-[1.02]
                  active:scale-95 transition
                "
                >
                  <Printer className="w-4 h-4" />
                  <span className="hidden sm:inline">Print Semua</span>
                  <span className="sm:hidden">Semua</span>
                </button>

              </div>
            </div>
          </div>
        </div>
      </motion.div>

      {/* ================= MODAL PILIH METODE ================= */}
      <AnimatePresence>
        {showAddOption && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm"
          >
            <motion.div
              initial={{ scale: 0.9, y: 30 }}
              animate={{ scale: 1, y: 0 }}
              exit={{ scale: 0.9, y: 30 }}
              className="w-[90%] max-w-md rounded-3xl p-px
              bg-linear-to-br from-green-200 via-white to-green-100"
            >
              <div className="rounded-3xl bg-white/90 backdrop-blur-2xl
              border border-white/60 shadow-2xl p-6 space-y-5">

                <h2 className="text-xl font-bold text-green-900 text-center">
                  🌾 Pilih Metode Input
                </h2>

                <div className="grid gap-3">

                  {/* MANUAL */}
                  <button
                    onClick={() => {
                      setShowAddOption(false);
                      window.location.href = "/inventory/create";
                    }}
                    className="p-4 rounded-2xl bg-linear-to-br from-green-100 to-white
                    border border-green-200 shadow hover:scale-[1.02] transition"
                  >
                    ✍️ Manual Input
                  </button>

                  {/* QR */}
                  <button
                    onClick={() => {
                      setShowAddOption(false);
                      setShowSelectLocation(true); // 🔥 buka modal pilih gudang
                    }}
                    className="p-4 rounded-2xl bg-linear-to-br from-emerald-100 to-white
                    border border-emerald-200 shadow hover:scale-[1.02] transition"
                  >
                    📷 Scan QR Code
                  </button>

                </div>

                <button
                  onClick={() => setShowAddOption(false)}
                  className="w-full text-sm text-gray-500 mt-2"
                >
                  Batal
                </button>

              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* ================= MODAL PILIH GUDANG ================= */}
      <AnimatePresence>
        {showSelectLocation && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm"
          >
            <motion.div
              initial={{ scale: 0.9, y: 30 }}
              animate={{ scale: 1, y: 0 }}
              exit={{ scale: 0.9, y: 30 }}
              className="w-[90%] max-w-md rounded-3xl p-px
              bg-linear-to-br from-green-200 via-white to-green-100"
            >
              <div className="rounded-3xl bg-white/95 backdrop-blur-2xl
              border border-white/60 shadow-2xl p-6 space-y-5">

                <h2 className="text-lg font-bold text-green-900 text-center">
                  🏬 Pilih Gudang
                </h2>

                <Select3D
                  fullWidth
                  value={selectedScanLocation}
                  onChange={setSelectedScanLocation}
                  placeholder="Pilih Gudang"
                  options={locations.map((l) => ({
                    label: l.name,
                    value: l.id,
                  }))}
                />

                <button
                  disabled={!selectedScanLocation}
                  onClick={() => {
                    // window.location.href = `/scan?location_id=${selectedScanLocation}`;
                    window.location.href = `/inventory/${selectedScanLocation}/scan`;
                  }}
                  className="
                  w-full py-3 rounded-xl
                  bg-linear-to-r from-emerald-600 to-green-500
                  text-white font-semibold
                  shadow hover:scale-[1.02] transition
                  disabled:opacity-40
                  "
                >
                  Lanjut Scan →
                </button>

                <button
                  onClick={() => setShowSelectLocation(false)}
                  className="w-full text-sm text-gray-500"
                >
                  Batal
                </button>

              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* ================= LOADING ================= */}
      {loading && (
        <div className="text-green-700 animate-pulse px-2">
          🌱 Loading stok...
        </div>
      )}

      {/* <InventoryTable data={datas} page={page} limit={limit} /> */}
      <InventoryTable data={datas} page={page} limit={limit}
            selectedItems={selectedItems} 
            toggleSelectItem={toggleSelectItem} handlePrintQr={handlePrintQr} />

      {/* ================= PAGINATION ================= */}
      <div className="flex flex-col md:flex-row justify-between items-center gap-3">

        <button
          disabled={page === 1}
          onClick={() => setPage((p) => p - 1)}
          className="px-4 py-2 rounded-xl
          bg-white/80 backdrop-blur-xl
          shadow-md border border-green-100
          hover:scale-105 active:scale-95 transition
          disabled:opacity-40"
        >
          ← Previous
        </button>

        <div className="text-sm text-green-900 font-medium">
          Page <b>{page}</b> / {totalPage}
        </div>

        <button
          disabled={page >= totalPage}
          onClick={() => setPage((p) => p + 1)}
          className="px-4 py-2 rounded-xl
          bg-white/80 backdrop-blur-xl
          shadow-md border border-green-100
          hover:scale-105 active:scale-95 transition
          disabled:opacity-40"
        >
          Next →
        </button>

      </div>

    </div>
  );
}

/* ================= INPUT ================= */
function Input({ value, onChange, placeholder }: any) {
  return (
    <input
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      className="px-3 py-2 rounded-xl border border-green-200 text-sm
      focus:outline-none focus:ring-2 focus:ring-green-400 bg-white/80
      shadow-inner backdrop-blur-md"
    />
  );
}