"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { motion } from "framer-motion";
import { Boxes, Truck, Hash } from "lucide-react";
import { useSession } from "next-auth/react";
import Loading from "@/app/components/Loading";

const PAGE_SIZE = 6;

export default function SupplierDetailPage() {
  const { id } = useParams();
  const router = useRouter();

  const { data: session, status } = useSession();
  const currentUser = session?.user as any;

  const [supplier, setSupplier] = useState<any>(null);
  const [items, setItems] = useState<any[]>([]);
  const [tab, setTab] = useState<"details" | "items">("details");
  const [page, setPage] = useState(1);

  // ✅ ADD DELETE STATE
  const [deleting, setDeleting] = useState(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"];
    if (!allowedRoles.includes(currentUser?.role)) {
      router.replace("/suppliers");
      return;
    }

    const load = async () => {
      const res = await fetch(`/api/suppliers/${id}`);
      const json = await res.json();

      console.log("Jsonnya: ", json);

      const supplierData = json?.data?.supplier || null;
      const itemsData = json?.data?.items || [];

      setSupplier(supplierData);
      setItems(itemsData);
    };

    if (id) load();
  }, [status, currentUser, id, router]);
  // }, [id]);

  
  if (!supplier) {
    return (
      <Loading pageName="Suppliers"/>
    );
  }
  // optional safety (biar tidak flash UI)
  if (!session) return null;

  const totalPages = Math.ceil(items.length / PAGE_SIZE);
  const start = (page - 1) * PAGE_SIZE;
  const paginatedItems = items.slice(start, start + PAGE_SIZE);

  return (
    <div className="min-h-screen p-6 bg-linear-to-b from-green-50 via-emerald-50 to-lime-50 relative overflow-hidden">

      <div className="absolute -top-40 -left-40 w-125 h-125 bg-green-300/20 blur-[160px]" />
      <div className="absolute bottom-0 right-0 w-125 h-125 bg-lime-300/20 blur-[160px]" />

      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative rounded-[40px] overflow-hidden shadow-[0_70px_180px_rgba(0,0,0,0.25)]"
      >
        <div className="absolute inset-0 bg-linear-to-br from-green-700 via-emerald-500 to-lime-400" />
        <div className="absolute inset-0 bg-white/10 backdrop-blur-2xl" />

        <div className="relative p-6 flex items-start justify-between">

          <div>
            <h1 className="text-2xl md:text-3xl font-bold text-white flex items-center gap-2">
              <Truck className="w-6 h-6" />
              🌾 {supplier.name}
            </h1>

            <p className="text-white/80 text-sm mt-1">
              Supplier Dashboard
            </p>
          </div>

          <div className="flex gap-2">

            <button
              onClick={() => router.back()}
              className="px-4 py-2 rounded-xl bg-white/20 text-white border border-white/30 hover:bg-white/30 transition text-sm"
            >
              ← Back
            </button>

            <button
              onClick={() => router.push(`/suppliers/${id}/edit`)}
              className="px-4 py-2 rounded-xl bg-yellow-400/90 text-black font-semibold hover:bg-yellow-300 transition text-sm"
            >
              ✏️ Edit
            </button>

            {/* ✅ DELETE FIXED */}
            <button
              disabled={deleting}
              onClick={async () => {
                const confirmDelete = confirm("Yakin ingin menghapus supplier ini?");
                if (!confirmDelete) return;

                try {
                  setDeleting(true);

                  const res = await fetch(`/api/suppliers/${id}`, {
                    method: "DELETE",
                  });

                  if (!res.ok) throw new Error("Delete failed");

                  alert("Supplier berhasil dihapus");
                  router.push("/suppliers");

                } catch (err) {
                  console.error(err);
                  alert("Gagal menghapus supplier");
                } finally {
                  setDeleting(false);
                }
              }}
              className={`px-4 py-2 rounded-xl text-sm font-semibold transition
                ${
                  deleting
                    ? "bg-red-300 text-white cursor-not-allowed"
                    : "bg-red-500/90 text-white hover:bg-red-400"
                }`}
            >
              {deleting ? "Deleting..." : "🗑 Delete"}
            </button>

          </div>
        </div>
      </motion.div>

      {/* TABS */}
      <div className="mt-6 flex gap-3">
        <TabButton
          active={tab === "details"}
          onClick={() => setTab("details")}
          icon={<Hash className="w-4 h-4" />}
          label="Details"
        />

        <TabButton
          active={tab === "items"}
          onClick={() => {
            setTab("items");
            setPage(1);
          }}
          icon={<Boxes className="w-4 h-4" />}
          label={`Items (${items.length})`}
        />
      </div>

      {/* CONTENT */}
      <div className="mt-6">

        {tab === "details" && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="rounded-[30px] p-6 bg-white/70 backdrop-blur-2xl shadow-xl border border-white/40"
          >
            <h2 className="text-lg font-bold text-green-800 mb-4">
              📦 Supplier Information
            </h2>

            <div className="space-y-3 text-sm text-gray-700">

              <Row label="Code" value={supplier.code} />
              <Row label="Contact Person" value={supplier.contact_person} />
              <Row label="Phone" value={supplier.phone} />
              <Row label="Email" value={supplier.email} />
              <Row label="City" value={supplier.city} />
              <Row label="Address" value={supplier.address} />

              <div className="mt-4 text-green-700 font-semibold flex items-center gap-2">
                <Boxes className="w-4 h-4" />
                Total Items: {supplier.total_items || 0}
              </div>
            </div>
          </motion.div>
        )}

        {/* ITEMS */}
        <div className="mt-8">

          <div className="flex items-center gap-2 mb-4 text-green-800 font-bold">
            <Boxes className="w-5 h-5" />
            Supplier Items
          </div>

          <div className="grid md:grid-cols-2 gap-4">

            {paginatedItems.length === 0 && (
              <div className="text-green-700">
                🌿 No items found
              </div>
            )}

            {paginatedItems.map((item, i) => (
              <motion.div
                key={item.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: i * 0.03 }}
                className="rounded-[26px] p-5 bg-white/70 backdrop-blur-2xl shadow-xl border border-white/40 hover:-translate-y-1 transition"
              >
                <div className="font-semibold text-green-900">
                  {item.nama_barang || item.name}
                </div>

                <div className="text-xs text-gray-500 mt-1">
                  Kode: {item.kode_barang || item.sku || "-"}
                </div>

                <div className="mt-2 text-xs text-green-700">
                  Kategori: {item.kategori_barang || item.category || "-"}
                </div>
              </motion.div>
            ))}
          </div>

          {items.length > PAGE_SIZE && (
            <div className="flex justify-center items-center gap-3 mt-6">

              <button
                disabled={page === 1}
                onClick={() => setPage((p) => p - 1)}
                className="px-4 py-2 rounded-xl bg-white/70 border text-green-700 disabled:opacity-40"
              >
                Prev
              </button>

              <div className="text-sm text-green-800 font-medium">
                Page {page} / {totalPages}
              </div>

              <button
                disabled={page === totalPages}
                onClick={() => setPage((p) => p + 1)}
                className="px-4 py-2 rounded-xl bg-white/70 border text-green-700 disabled:opacity-40"
              >
                Next
              </button>

            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* TAB */
function TabButton({ active, onClick, icon, label }: any) {
  return (
    <button
      onClick={onClick}
      className={`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold transition
      ${
        active
          ? "bg-green-600 text-white shadow-lg"
          : "bg-white/70 text-green-700 hover:bg-green-100"
      }`}
    >
      {icon}
      {label}
    </button>
  );
}

/* ROW */
function Row({ label, value }: any) {
  return (
    <div className="flex justify-between border-b border-green-100 py-2">
      <span className="text-gray-500">{label}</span>
      <span className="text-green-900 font-medium">
        {value || "-"}
      </span>
    </div>
  );
}