"use client";

import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import Link from "next/link";
import { Plus } from "lucide-react";
import { ItemsTable } from "./ItemTable";
import { Select3D } from "../components/Select3D";

import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Loading from "../components/Loading";
import { Printer, CheckSquare } from "lucide-react";

/* ================= TYPES ================= */
type Item = {
  id: number;
  sku: string;
  name: string;
  category: string;
  unit: string;
  is_active: boolean;
  description: string;
  barcode: string | null;
};

export default function ItemsPage() {

  const { data: session, status } = useSession();
  const router = useRouter();
  const currentUser = session?.user as any;
  const [selectedItems, setSelectedItems] = useState<number[]>([]);
  const [data, setData] = useState<Item[]>([]);
  const [categories, setCategories] = useState<string[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  const [search, setSearch] = useState("");
  const [category, setCategory] = useState("ALL");

  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);

  /* ================= FETCH ================= */
  const fetchData = async () => {
    setLoading(true);

    const res = await fetch(
      `/api/items?search=${search}&category=${category}&page=${page}&limit=${limit}`,
      {
        cache: "no-store",
      }
    );

    const json = await res.json();

    setData(json.items);
    setCategories(json.categories);
    setTotal(json.total);

    setLoading(false);
  };

  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("/satuan");
      return;
    }

    fetchData();
  }, [search, category, page, limit, status, router]);

  const totalPage = Math.ceil(total / limit);
  const toggleSelectItem = (id: number) => {
    setSelectedItems((prev) =>
      prev.includes(id)
        ? prev.filter((x) => x !== id)
        : [...prev, id]
    );
  };

  const selectAllCurrentPage = () => {
    setSelectedItems(data.map((x) => x.id));
  };

  const clearSelection = () => {
    setSelectedItems([]);
  };
  
  const handlePrintMultipleQr = (type: "selected" | "all") => {
    const items =
      type === "all"
        ? data
        : data.filter((x) => selectedItems.includes(x.id));

    if (items.length === 0) {
      alert("Pilih item dulu");
      return;
    }

    const win = window.open("", "_blank", "width=1000,height=800");
    if (!win) return;

   const html = items
      .filter((x) => x.barcode)
      .map(
        (item) => `
        <div class="card">
          <div class="name">${item.name}</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 Multi QR Code</title>
         <style>
            @page{
              size:A4 portrait;
              margin:8mm;
            }

            body{
              font-family:Arial;
              padding:12px;
              margin:0;
            }

            .grid{
              display:grid;
              grid-template-columns:repeat(4,1fr); /* 4 kolom */
              gap:10px;
            }

            .card{
              border:1px solid #ddd;
              border-radius:8px;
              padding:8px;
              text-align:center;
              page-break-inside:avoid;
              break-inside:avoid;
            }

            .name{
              font-size:11px;
              font-weight:bold;
              min-height:28px;
              line-height:1.2;
              overflow:hidden;
            }

            img{
              width:120px;
              height:120px;
              margin:4px auto;
              display:block;
            }

            .code{
              margin-top:4px;
              font-size:10px;
              word-break:break-all;
              line-height:1.1;
            }

            .toolbar{
              margin-bottom:14px;
            }

            button{
              padding:8px 12px;
              border:none;
              border-radius:8px;
              cursor:pointer;
              font-weight:600;
              margin-right:8px;
            }

            .print{background:#16a34a;color:white;}
            .close{background:#e5e7eb;}

            @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();
  };
  // optional safety (biar tidak flash UI)
  if (!session) return null;

  return (
    <div className="space-y-6 p-4">

      {/* ================= HEADER ================= */}
     <motion.div
        initial={{ opacity: 0, y: 30, scale: 0.98 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        transition={{ duration: 0.45 }}
        className="relative overflow-hidden rounded-[28px]"
      >
        {/* BACKGROUND */}
        <div className="absolute inset-0 bg-linear-to-br from-green-300 via-emerald-200 to-lime-200" />
        <div className="absolute inset-0 opacity-[0.07] bg-[url('https://www.transparenttextures.com/patterns/soil.png')]" />

        {/* LIGHT EFFECT */}
        <div className="absolute -top-24 -left-10 w-72 h-72 bg-green-400/30 blur-[120px]" />
        <div className="absolute bottom-0 right-0 w-72 h-72 bg-lime-300/30 blur-[140px]" />
        <div className="absolute inset-0 bg-white/25 backdrop-blur-2xl" />

        {/* CARD */}
        <div
          className="relative z-10 rounded-[28px] border border-white/40
          bg-white/65 backdrop-blur-2xl
          shadow-[0_25px_80px_rgba(0,0,0,0.18)]
          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="space-y-2 min-w-55">
              <h1 className="text-2xl sm:text-3xl font-bold text-green-900 tracking-tight leading-tight">
                🌾 Master Items
              </h1>

              <p className="text-sm sm:text-base text-green-800/75">
                Total Data :{" "}
                <span className="font-bold text-green-900">
                  {new Intl.NumberFormat("id-ID").format(total)}
                </span>
              </p>

              <div className="h-1.5 w-24 rounded-full bg-linear-to-r from-green-500 to-lime-400" />
            </div>

            {/* RIGHT */}
            <div className="flex-1 space-y-3">
              
              {/* FILTER */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                <Input
                  value={search}
                  onChange={(v: string) => {
                    setPage(1);
                    setSearch(v);
                  }}
                  placeholder="Cari Nama/SKU item..."
                />

                <Select3D
                  fullWidth
                  value={category}
                  onChange={(v) => {
                    setPage(1);
                    setCategory(v);
                  }}
                  options={[
                    { label: "Semua Kategori", value: "ALL" },
                    ...categories.map((c) => ({
                      label: c,
                      value: c,
                    })),
                  ]}
                  placeholder="Kategori"
                />

                <Select3D
                  value={limit}
                  onChange={(v) => {
                    setPage(1);
                    setLimit(Number(v));
                  }}
                  options={[
                    { label: "10", value: 10 },
                    { label: "20", value: 20 },
                    { label: "50", value: 50 },
                    { label: "100", value: 100 },
                  ]}
                  placeholder="Limit"
                />
              </div>

              {/* ACTION BUTTONS */}
              <div className="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-3">
                
                <Link
                  href="/items/tambah"
                  className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl
                  bg-linear-to-r from-green-600 via-emerald-500 to-lime-500
                  text-white text-sm font-semibold
                  shadow-[0_10px_25px_rgba(34,197,94,0.28)]
                  hover:scale-[1.02] active:scale-95 transition"
                >
                  <Plus className="w-4 h-4" />
                  Tambah
                </Link>

                <button
                  onClick={() => handlePrintMultipleQr("selected")}
                  className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl
                  bg-linear-to-r from-indigo-600 to-blue-500
                  text-white text-sm font-semibold
                  shadow hover:scale-[1.02] active:scale-95 transition"
                >
                  <Printer className="w-4 h-4" />
                  Print Pilihan
                </button>

                <button
                  onClick={() => handlePrintMultipleQr("all")}
                  className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl
                  bg-linear-to-r from-slate-700 to-slate-600
                  text-white text-sm font-semibold
                  shadow hover:scale-[1.02] active:scale-95 transition"
                >
                  <Printer className="w-4 h-4" />
                  Print Semua
                </button>

                <button
                  onClick={selectAllCurrentPage}
                  className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl
                  bg-white/90 border border-gray-200
                  text-sm font-semibold text-gray-700
                  shadow hover:bg-white transition"
                >
                  <CheckSquare className="w-4 h-4" />
                  Pilih Semua
                </button>

                <button
                  onClick={clearSelection}
                  className="px-4 py-3 rounded-xl
                  bg-white/90 border border-gray-200
                  text-sm font-semibold text-gray-700
                  shadow hover:bg-white transition"
                >
                  Clear
                </button>

              </div>
            </div>
          </div>
        </div>
      </motion.div>

      {/* ================= TABLE ================= */}
      {loading ? (
        <Loading pageName="Data Items"/>
      ) : (
        // <ItemsTable data={data} page={page} limit={limit} />
        <ItemsTable data={data} page={page} limit={limit} selectedItems={selectedItems} toggleSelectItem={toggleSelectItem} />
      )}

      {/* ================= PAGINATION ================= */}
      <div className="flex justify-between items-center">

        <button
          disabled={page === 1}
          onClick={() => setPage(page - 1)}
          className="px-4 py-2 rounded-xl bg-white/80 shadow disabled:opacity-40"
        >
          ← Prev
        </button>

        <div className="text-sm text-green-900">
          Page {page} / {totalPage || 1}
        </div>

        <button
          disabled={page >= totalPage}
          onClick={() => setPage(page + 1)}
          className="px-4 py-2 rounded-xl bg-white/80 shadow disabled:opacity-40"
        >
          Next →
        </button>

      </div>

    </div>
  );
}

/* ================= INPUT (GREEN GLOW) ================= */
function Input({ value, onChange, placeholder }: any) {
  return (
    <div className="relative group">
      {/* glow */}
      <div className="absolute inset-0 translate-y-1 bg-green-300/20 blur-lg rounded-xl" />

      <input
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        className="relative px-4 py-2 rounded-xl
        bg-white/80 backdrop-blur-xl
        border border-green-200
        text-sm shadow-md
        focus:outline-none focus:ring-2 focus:ring-green-400
        transition"
      />
    </div>
  );
}

/* ================= SELECT (GREEN OUTLINE FIX) ================= */
function Select({ value, onChange, children }: any) {
  return (
    <div className="relative group">
      {/* glow */}
      <div className="absolute inset-0 translate-y-1 bg-green-300/20 blur-lg rounded-xl" />

      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="relative px-3 py-2 rounded-xl
        bg-white/80 backdrop-blur-xl
        border border-green-200
        text-sm shadow-md
        focus:outline-none focus:ring-2 focus:ring-green-400
        transition"
      >
        {children}
      </select>
    </div>
  );
}