"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { motion } from "framer-motion";
import {
  ArrowLeft,
  Boxes,
  Warehouse,
  Layers3,
  Grid3X3,
  CheckCircle2,
  Ban,
  Pencil,
  RefreshCcw,
  CalendarDays,
  Package2,
  MapPinned,
  ShieldCheck,
  ClipboardList,
  Building2,
} from "lucide-react";
import { formatWIB } from "@/app/lib/formatWIB";
import { useSession } from "next-auth/react";

type DetailData = {
  id: number;
  location_id: number;
  location_code: string;
  location_name: string;
  location_type: string;
  location_address: string | null;

  code: string;
  name: string;
  type: "RACK" | "BIN" | "AREA" | "SHELF" | "PALLET";
  is_active: number | boolean | string;

  created_at: string;
  updated_at: string;

  total_items?: number;
  total_qty?: number;
};

export default function LocationBinDetailPage() {
  const params = useParams();
  const router = useRouter();

  const id = params?.id;

  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<DetailData | null>(null);

  
  async function loadData() {
    try {
      setLoading(true);

      const res = await fetch(`/api/location-bins/${id}`, {
        cache: "no-store",
      });

      const json = await res.json();

      if (!res.ok) {
        alert(json.message || "Data not found");
        router.push("/location-bins");
        return;
      }

      setData(json.data || null);
    } catch (error) {
      console.error(error);
      alert("Server error");
      router.push("/location-bins");
    } finally {
      setLoading(false);
    }
  }

   const { data: session, status } = useSession();
  const currentUser = session?.user as any;

  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("/location-bins");
      return;
    }

    if (id) loadData();
  }, [id, status]);


  const active = useMemo(() => {
    if (!data) return false;

    return (
      data.is_active === true ||
      data.is_active === 1 ||
      data.is_active === "1"
    );
  }, [data]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-green-50 via-emerald-50 to-lime-50">
        <div className="flex items-center gap-3 px-6 py-4 rounded-2xl bg-white shadow-2xl border border-emerald-100 backdrop-blur-xl">
          <RefreshCcw size={18} className="animate-spin text-emerald-600" />
          <span className="font-semibold text-emerald-800">
            Loading location bin...
          </span>
        </div>
      </div>
    );
  }

  if (!data) return null;

  return (
    <div className="min-h-screen p-4 md:p-6 space-y-6 bg-[radial-gradient(circle_at_top,#d1fae5,transparent_40%),radial-gradient(circle_at_bottom,#bae6fd,transparent_40%),linear-gradient(to_br,#f0fdf4,#fefce8,#eff6ff)]">
      {/* HERO */}
    <motion.div
        initial={{ opacity: 0, y: 20, scale: 0.98 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        className="relative overflow-hidden rounded-[34px]"
      >
        {/* layered background */}
        <div className="absolute inset-0 bg-linear-to-br from-emerald-400 via-lime-300 to-sky-300 opacity-90" />
        <div className="absolute inset-0 bg-white/20 backdrop-blur-2xl" />

        {/* soft glow */}
        <div className="absolute -top-20 -left-20 h-80 w-80 bg-emerald-400/30 blur-[120px]" />
        <div className="absolute -bottom-20 -right-20 h-80 w-80 bg-sky-400/25 blur-[140px]" />
        <div className="absolute top-10 right-20 h-40 w-40 rounded-full bg-white/20 blur-3xl" />

        {/* card */}
        <div className="relative rounded-[34px] border border-white/55 bg-white/45 p-5 md:p-8 backdrop-blur-2xl shadow-[0_40px_120px_rgba(16,185,129,0.16)]">
          
          {/* glossy line */}
          <div className="absolute top-0 left-8 right-8 h-px bg-white/90" />

          <div className="flex flex-col gap-6 xl:flex-row xl:items-center xl:justify-between">
            
            {/* left content */}
            <div className="min-w-0">
              <div className="inline-flex items-center gap-2 rounded-full border border-white/70 bg-linear-to-r from-white/90 via-emerald-50/90 to-lime-50/80 px-4 py-2 text-sm font-semibold text-emerald-800 shadow-[0_12px_24px_rgba(16,185,129,0.10)]">
                <span className="flex h-6 w-6 items-center justify-center rounded-full bg-linear-to-br from-emerald-500 to-lime-500 text-white shadow-md">
                  <Grid3X3 size={13} />
                </span>
                Detail Area Gudang
              </div>

              <h1 className="mt-4 text-4xl md:text-6xl font-black tracking-tight leading-tight wrap-break-word">
                <span className="bg-linear-to-r from-green-950 via-emerald-700 to-lime-600 bg-clip-text text-transparent drop-shadow-[0_18px_35px_rgba(16,185,129,0.16)]">
                  {data.code}
                </span>
              </h1>

              <p className="mt-2 max-w-2xl text-sm md:text-base leading-relaxed text-emerald-950/80">
                Detail lokasi penyimpanan profesional untuk perpindahan barang,
                stock opname, serta pengelolaan struktur gudang yang rapi dan
                terorganisir.
              </p>
            </div>

            {/* right buttons */}
            <div className="flex flex-col sm:flex-row gap-3 w-full xl:w-auto">
              <Link
                href="/location-bins"
                className="group inline-flex items-center justify-center gap-2 rounded-2xl border border-white/70 bg-linear-to-r from-white/95 to-emerald-50/85 px-5 py-3 text-emerald-900 font-semibold shadow-[0_14px_28px_rgba(16,185,129,0.10)] transition hover:-translate-y-1"
              >
                <span className="flex h-8 w-8 items-center justify-center rounded-xl bg-linear-to-br from-emerald-500 to-lime-500 text-white shadow-md">
                  <ArrowLeft
                    size={16}
                    className="transition group-hover:-translate-x-0.5"
                  />
                </span>
                Kembali
              </Link>

              <Link
                href={`/location-bins/${data.id}/edit`}
                className="group inline-flex items-center justify-center gap-2 rounded-2xl bg-linear-to-r from-amber-400 via-orange-400 to-yellow-500 px-5 py-3 text-white font-bold shadow-[0_18px_50px_rgba(245,158,11,0.42)] transition hover:-translate-y-1"
              >
                <span className="flex h-8 w-8 items-center justify-center rounded-xl bg-white/20 backdrop-blur text-white">
                  <Pencil size={16} />
                </span>
                Edit
              </Link>
            </div>
          </div>
        </div>
      </motion.div>

      {/* STATS */}
   <div className="grid gap-4 md:gap-5 sm:grid-cols-2 xl:grid-cols-4">
        <CardStat
          title="ID Area"
          value={String(data.id)}
          icon={<Boxes size={22} />}
          gradient="from-sky-500 via-cyan-500 to-blue-600"
        />

        <CardStat
          title="Tipe"
          value={data.type}
          icon={<Layers3 size={22} />}
          gradient="from-violet-500 via-fuchsia-500 to-pink-500"
        />

        <CardStat
          title="Status"
          value={active ? "AKTIF" : "NONAKTIF"}
          icon={
            active ? (
              <CheckCircle2 size={22} />
            ) : (
              <Ban size={22} />
            )
          }
          gradient={
            active
              ? "from-emerald-500 via-green-500 to-lime-500"
              : "from-rose-500 via-red-500 to-orange-500"
          }
        />

        <CardStat
          title="Item"
          value={String(data.total_items || 0)}
          icon={<Package2 size={22} />}
          gradient="from-amber-500 via-orange-400 to-yellow-500"
        />
      </div>
      {/* CONTENT */}
    <div className="grid gap-5 md:gap-6 xl:grid-cols-3">
  
        {/* LEFT SIDE */}
        <div className="xl:col-span-2 space-y-5 md:space-y-6">
          
          <SectionCard
            title="Informasi Bin"
            icon={<ClipboardList size={18} />}
          >
            <InfoGrid
              items={[
                ["Kode Area", data.code],
                ["Nama Area", data.name],
                ["Tipe Area", data.type],
                ["Status", active ? "AKTIF" : "NONAKTIF"],
                ["Dibuat Pada", formatWIB(data.created_at)],
                ["Diupdate Pada", formatWIB(data.updated_at)],
              ]}
            />
          </SectionCard>

          <SectionCard
            title="Informasi Gudang"
            icon={<Warehouse size={18} />}
          >
            <InfoGrid
              items={[
                ["Kode Gudang", data.location_code],
                ["Nama Gudang", data.location_name],
                ["Tipe Gudang", data.location_type],
                ["Alamat", data.location_address || "-"],
              ]}
            />
          </SectionCard>
        </div>

        {/* RIGHT SIDE */}
        <div className="space-y-5 md:space-y-6">
          
          <SectionCard
            title="Status Cepat"
            icon={<ShieldCheck size={18} />}
          >
            <div className="space-y-4">
              <StatusRow
                label="Ketersediaan"
                active={active}
              />

              <StatusRow
                label="Siap Opname"
                active={active}
              />

              <StatusRow
                label="Siap Inventory"
                active={true}
              />
            </div>
          </SectionCard>

          <SectionCard
            title="Ringkasan"
            icon={<Building2 size={18} />}
          >
            <div className="space-y-4 text-sm">
              <SummaryRow
                icon={<MapPinned size={16} />}
                label="Gudang"
                value={data.location_name}
              />

              <SummaryRow
                icon={<Boxes size={16} />}
                label="Kode Penyimpanan"
                value={data.code}
              />

              <SummaryRow
                icon={<CalendarDays size={16} />}
                label="Update Terakhir"
                value={formatWIB(data.updated_at)}
              />
            </div>
          </SectionCard>
        </div>
      </div>
    </div>
  );
}

/* COMPONENTS */

function CardStat({ title, value, icon, gradient }: any) {
  return (
    <motion.div
      whileHover={{ y: -6, scale: 1.02 }}
      className="relative rounded-3xl overflow-hidden border border-white/60 bg-white/70 backdrop-blur-2xl shadow-[0_25px_60px_rgba(0,0,0,0.12)] p-5"
    >
      <div className={`absolute -right-6 -top-6 w-28 h-28 rounded-full bg-gradient-to-br ${gradient} opacity-20 blur-2xl`} />

      <div className="flex items-center justify-between relative">
        <div>
          <p className="text-sm text-emerald-700/70">{title}</p>
          <h3 className="text-3xl font-black text-emerald-950 mt-2">{value}</h3>
        </div>

        <div className={`h-14 w-14 rounded-2xl bg-gradient-to-br ${gradient} text-white flex items-center justify-center shadow-xl`}>
          {icon}
        </div>
      </div>
    </motion.div>
  );
}

function SectionCard({ title, icon, children }: any) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 14 }}
      animate={{ opacity: 1, y: 0 }}
      className="rounded-3xl border border-white/60 bg-white/70 backdrop-blur-2xl shadow-[0_25px_70px_rgba(0,0,0,0.10)] overflow-hidden"
    >
      <div className="px-6 py-5 flex items-center gap-3 border-b border-emerald-100 bg-white/40">
        <div className="h-10 w-10 rounded-2xl bg-emerald-100 text-emerald-700 flex items-center justify-center shadow-inner">
          {icon}
        </div>
        <h2 className="font-black text-emerald-900">{title}</h2>
      </div>

      <div className="p-6">{children}</div>
    </motion.div>
  );
}

function InfoGrid({ items }: { items: string[][] }) {
  return (
    <div className="grid gap-4 md:grid-cols-2">
      {items.map(([label, value]) => (
        <div key={label} className="rounded-2xl border border-emerald-100 bg-emerald-50/40 p-4 shadow-inner">
          <p className="text-xs font-semibold uppercase text-emerald-700/70">{label}</p>
          <p className="mt-2 font-bold text-emerald-950 break-words">{value}</p>
        </div>
      ))}
    </div>
  );
}

function StatusRow({ label, active }: { label: string; active: boolean }) {
  return (
    <div className="flex items-center justify-between rounded-2xl border border-emerald-100 bg-white/60 px-4 py-3 shadow-sm">
      <span className="text-sm font-medium text-emerald-900">{label}</span>

      {active ? (
        <span className="px-3 py-1 rounded-full text-xs font-bold bg-emerald-100 text-emerald-800 border border-emerald-200">
          YES
        </span>
      ) : (
        <span className="px-3 py-1 rounded-full text-xs font-bold bg-rose-100 text-rose-700 border border-rose-200">
          NO
        </span>
      )}
    </div>
  );
}

function SummaryRow({ icon, label, value }: any) {
  return (
    <div className="flex items-start gap-3 rounded-2xl border border-emerald-100 bg-white/60 p-4 shadow-sm">
      <div className="h-9 w-9 rounded-xl bg-emerald-50 border border-emerald-100 flex items-center justify-center text-emerald-700">
        {icon}
      </div>

      <div>
        <p className="text-xs font-semibold uppercase text-emerald-700/70">{label}</p>
        <p className="mt-1 font-bold text-emerald-950 break-words">{value}</p>
      </div>
    </div>
  );
}