"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { motion } from "framer-motion";
import { Select3D } from "../components/Select3D";
import { formatWIB } from "../lib/formatWIB";
import {
  Search,
  Plus,
  RefreshCcw,
  Warehouse,
  Boxes,
  Layers3,
  MapPinned,
  Eye,
  Pencil,
  CheckCircle2,
  Ban,
  Filter,
  TrendingUp,
  Package2,
  Grid3X3,
} from "lucide-react";

import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Loading from "../components/Loading";
type BinType = "RACK" | "BIN" | "AREA" | "SHELF" | "PALLET";

type LocationBin = {
  id: number;
  location_id: number; // tambahkan ini
  code: string;
  name: string;
  type: BinType;
  is_active: number | boolean;
  warehouse_name: string;
  created_at: string;
};

export default function LocationBinsPage() {
  const [loading, setLoading] = useState(true);
  const [keyword, setKeyword] = useState("");
  const [type, setType] = useState("ALL");
  const [statuses, setStatus] = useState("ALL");
  const [data, setData] = useState<LocationBin[]>([]);

  const [warehouse, setWarehouse] = useState("ALL");
  const [warehouses, setWarehouses] = useState<any[]>([]);
 const { data: session, status } = useSession();
 const router = useRouter();
 const currentUser = session?.user as any;
  async function loadWarehouses() {
    try {
      const res = await fetch("/api/gudang?page=1&limit=999", {
        cache: "no-store",
      });

      const json = await res.json();

      setWarehouses(json.locations || []);
    } catch (error) {
      console.error(error);
      setWarehouses([]);
    }
  }
  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("/");
      return;
    }

    loadData();
    loadWarehouses();
  }, [status]);

  async function loadData() {
    try {
      setLoading(true);

      const res = await fetch("/api/location-bins", {
        cache: "no-store",
      });

      const json = await res.json();

      setData(json.data || []);
    } catch (err) {
      console.error(err);
      setData([]);
    } finally {
      setLoading(false);
    }
  }

  const filtered = useMemo(() => {
    return data.filter((row) => {
      const q = keyword.toLowerCase();

      const matchKeyword =
        row.code.toLowerCase().includes(q) ||
        row.name.toLowerCase().includes(q) ||
        row.warehouse_name.toLowerCase().includes(q);

      const matchType =
        type === "ALL" ? true : row.type === type;

      const matchWarehouse =
        warehouse === "ALL"
          ? true
          : String(row.location_id) === warehouse;

      const active =
        row.is_active === true ||
        row.is_active === 1;

      const matchStatus =
        statuses === "ALL"
          ? true
          : statuses === "ACTIVE"
          ? active
          : !active;

      return (
        matchKeyword &&
        matchType &&
        matchWarehouse &&
        matchStatus
      );
    });
  }, [data, keyword, type, warehouse, statuses]);

  const stats = useMemo(() => {
    const active = data.filter(
      (x) =>
        x.is_active === true ||
        x.is_active === 1
    ).length;

    return {
      total: data.length,
      active,
      inactive: data.length - active,
      rack: data.filter((x) => x.type === "RACK").length,
    };
  }, [data]);

  function badgeType(value: string) {
    const base =
      "px-3 py-1 rounded-full text-[11px] font-bold border inline-flex items-center gap-1";

    switch (value) {
      case "RACK":
        return `${base} bg-blue-50 text-blue-700 border-blue-200`;
      case "BIN":
        return `${base} bg-emerald-50 text-emerald-700 border-emerald-200`;
      case "AREA":
        return `${base} bg-purple-50 text-purple-700 border-purple-200`;
      case "SHELF":
        return `${base} bg-amber-50 text-amber-700 border-amber-200`;
      case "PALLET":
        return `${base} bg-rose-50 text-rose-700 border-rose-200`;
      default:
        return `${base} bg-slate-50 text-slate-700 border-slate-200`;
    }
  }

  function badgeStatus(active: any) {
    const isActive =
      active === true || active === 1 || active === "1";

    return isActive
      ? "px-3 py-1 rounded-full text-[11px] font-bold border bg-emerald-50 text-emerald-700 border-emerald-200"
      : "px-3 py-1 rounded-full text-[11px] font-bold border bg-red-50 text-red-700 border-red-200";
  }

  return (
    <div className="min-h-screen bg-[radial-gradient(circle_at_top_right,#bfdbfe,transparent_30%),radial-gradient(circle_at_bottom_left,#bbf7d0,transparent_35%),linear-gradient(to_bottom_right,#eff6ff,#f8fafc,#ecfeff)] p-4 md:p-6 space-y-6">
      {/* HERO */}
      <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          className="relative overflow-hidden rounded-[30px]"
        >
          {/* background */}
          <div className="absolute inset-0 bg-linear-to-br from-emerald-400 via-lime-300 to-sky-300" />
          <div className="absolute inset-0 bg-white/20 backdrop-blur-3xl" />

          {/* glow */}
          <div className="absolute -left-20 top-0 h-72 w-72 bg-emerald-500/25 blur-[120px]" />
          <div className="absolute right-0 bottom-0 h-72 w-72 bg-lime-400/25 blur-[140px]" />
          <div className="absolute top-10 right-20 h-32 w-32 rounded-full bg-white/20 blur-3xl" />
          <div className="absolute bottom-6 left-10 h-28 w-28 rounded-full bg-sky-300/20 blur-3xl" />

          {/* glass card */}
          <div className="relative z-10 rounded-[30px] border border-white/45 bg-white/55 p-6 md:p-8 backdrop-blur-2xl shadow-[0_30px_90px_rgba(16,185,129,0.18)]">
            <div className="absolute top-0 left-8 right-8 h-px bg-white/90" />

            <div className="flex flex-col xl:flex-row gap-6 xl:items-center xl:justify-between">
              
              {/* left */}
              <div>
                <div className="group relative inline-flex items-center gap-2.5 overflow-hidden rounded-full border border-white/70 bg-linear-to-r from-white/90 via-emerald-50/85 to-lime-50/80 px-4 py-2 text-sm font-semibold text-emerald-900 shadow-[0_10px_24px_rgba(16,185,129,0.12)] backdrop-blur-xl">
                  <span className="absolute inset-0 bg-linear-to-tr from-white/40 via-transparent to-lime-100/30" />

                  <span className="relative z-10 flex h-7 w-7 items-center justify-center rounded-full bg-linear-to-br from-emerald-500 to-lime-500 text-white shadow-md">
                    <Grid3X3 size={14} />
                  </span>

                  <span className="relative z-10">
                    Area Gudang
                  </span>
                </div>

                <h1 className="mt-4 text-3xl md:text-5xl font-black tracking-tight leading-tight">
                  <span className="bg-linear-to-r from-green-950 via-emerald-800 to-lime-600 bg-clip-text text-transparent drop-shadow-[0_18px_35px_rgba(16,185,129,0.16)]">
                    Manajemen Area
                  </span>
                </h1>

                <p className="mt-2 max-w-2xl text-sm md:text-base leading-relaxed text-emerald-950/75">
                  Kelola rak, bin, shelf, zona pallet dan Area Gudang DSR.
                </p>
              </div>

              {/* right */}
              <div className="flex flex-wrap gap-3">
                <button
                  onClick={loadData}
                  className="group relative overflow-hidden rounded-2xl border border-white/70 bg-white/80 px-5 py-3 font-semibold text-emerald-900 shadow-[0_14px_28px_rgba(16,185,129,0.12)] backdrop-blur-xl transition hover:-translate-y-0.5 hover:shadow-[0_20px_34px_rgba(16,185,129,0.18)]"
                >
                  <span className="inline-flex items-center gap-2">
                    <RefreshCcw
                      size={17}
                      className="group-hover:rotate-180 transition duration-500"
                    />
                    Muat Ulang
                  </span>
                </button>

                <Link
                  href="/location-bins/create"
                  className="group relative overflow-hidden rounded-2xl bg-linear-to-r from-emerald-600 via-green-500 to-lime-500 px-5 py-3 font-bold text-white shadow-[0_18px_40px_rgba(34,197,94,0.35)] transition hover:-translate-y-0.5 hover:shadow-[0_24px_48px_rgba(34,197,94,0.45)]"
                >
                  <span className="absolute inset-0 bg-linear-to-tr from-white/20 via-transparent to-lime-200/20" />
                  <span className="relative inline-flex items-center gap-2">
                    <Plus size={18} />
                    Area Baru
                  </span>
                </Link>
              </div>
            </div>
          </div>
        </motion.div>

      {/* STATS */}
      <div className="grid gap-5 md:grid-cols-2 xl:grid-cols-4">
        <Card
          title="Total Area"
          value={stats.total}
          icon={<Boxes size={22} />}
          gradient="from-sky-500 to-blue-600"
        />

        <Card
          title="Active"
          value={stats.active}
          icon={<CheckCircle2 size={22} />}
          gradient="from-emerald-500 to-green-600"
        />

        <Card
          title="Inactive"
          value={stats.inactive}
          icon={<Ban size={22} />}
          gradient="from-rose-500 to-red-600"
        />

        <Card
          title="Rack Type"
          value={stats.rack}
          icon={<Layers3 size={22} />}
          gradient="from-violet-500 to-purple-600"
        />
      </div>

      {/* FILTER */}
   <motion.div
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      className="relative overflow-hidden rounded-3xl"
    >
      {/* background depth */}
      <div className="absolute inset-0 bg-white/75 backdrop-blur-2xl" />
      <div className="absolute -top-10 left-10 h-28 w-28 rounded-full bg-emerald-300/15 blur-3xl" />
      <div className="absolute bottom-0 right-10 h-32 w-32 rounded-full bg-lime-300/15 blur-3xl" />
      <div className="absolute inset-x-8 top-0 h-px bg-white/90" />

      {/* <div className="relative p-4 md:p-5 grid gap-4 sm:grid-cols-2 xl:grid-cols-4"> */}
      <div className="relative p-4 md:p-5 grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
        
        {/* Search */}
        <div className="sm:col-span-2 xl:col-span-1">
          <GlassInput
            icon={<Search size={18} />}
            value={keyword}
            onChange={(e: any) => setKeyword(e.target.value)}
            placeholder="Cari kode, nama, gudang..."
          />
        </div>
        
      {/* tambahkan di FILTER SECTION (antara Type dan Status) */}
      <div>
        <FilterSelect
          value={warehouse}
          onChange={setWarehouse}
          options={[
            { label: "Semua Gudang", value: "ALL" },
            ...warehouses.map((item) => ({
              label: `${item.code} - ${item.name}`,
              value: String(item.id),
            })),
          ]}
        />
      </div>
        {/* Type */}
        <div>
          <FilterSelect
            value={type}
            onChange={setType}
            options={[
              { label: "Semua Tipe", value: "ALL" },
              { label: "Rak", value: "RACK" },
              { label: "Bin", value: "BIN" },
              { label: "Area", value: "AREA" },
              { label: "Shelf", value: "SHELF" },
              { label: "Pallet", value: "PALLET" },
            ]}
          />
        </div>

        {/* Status */}
        <div>
          <FilterSelect
            value={statuses}
            onChange={setStatus}
            options={[
              { label: "Semua Status", value: "ALL" },
              { label: "Aktif", value: "ACTIVE" },
              { label: "Nonaktif", value: "INACTIVE" },
            ]}
          />
        </div>

        {/* Result */}
        <div className="rounded-2xl border border-emerald-100 bg-linear-to-br from-emerald-50 via-white to-lime-50 px-5 py-3 shadow-[0_12px_28px_rgba(16,185,129,0.10)] flex items-center justify-between">
          <div>
            <p className="text-xs font-medium text-slate-500">
              Hasil Filter
            </p>

            <p className="text-2xl md:text-3xl font-black bg-linear-to-r from-green-950 via-emerald-700 to-lime-600 bg-clip-text text-transparent">
              {filtered.length}
            </p>
          </div>

          <div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-white shadow-md border border-emerald-100">
            <TrendingUp className="text-emerald-600" size={20} />
          </div>
        </div>
      </div>
    </motion.div>

      {/* TABLE */}
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      className="relative overflow-hidden rounded-3xl"
    >
      {/* ambient glow */}
      <div className="absolute inset-0 translate-y-5 rounded-3xl bg-emerald-300/10 blur-3xl" />
      <div className="absolute -top-10 right-10 h-32 w-32 rounded-full bg-lime-300/15 blur-3xl" />
      <div className="absolute bottom-0 left-10 h-36 w-36 rounded-full bg-sky-300/15 blur-3xl" />

      {/* main card */}
      <div className="relative overflow-hidden rounded-3xl border border-white/60 bg-white/85 backdrop-blur-2xl shadow-[0_25px_60px_rgba(16,185,129,0.12)]">
        
        {/* glossy line */}
        <div className="absolute top-0 left-6 right-6 h-px bg-white/95" />

        {/* header */}
        <div className="px-4 sm:px-6 py-4 sm:py-5 border-b border-emerald-100/70 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div className="min-w-0">
            <h2 className="text-lg sm:text-xl md:text-2xl font-black tracking-tight bg-linear-to-r from-green-950 via-emerald-700 to-lime-600 bg-clip-text text-transparent">
              Daftar Area Gudang
            </h2>

            <p className="text-xs sm:text-sm text-slate-500 mt-1">
              Area Gudang di Gudang DSR
            </p>
          </div>

          <div className="inline-flex w-fit items-center gap-2 rounded-full border border-emerald-100 bg-linear-to-r from-white to-emerald-50 px-4 py-2 text-xs sm:text-sm text-emerald-700 shadow-sm">
            <Package2 size={15} />
            Data Langsung
          </div>
        </div>

        {/* ================= MOBILE CARD ================= */}
        <div className="block lg:hidden p-4 space-y-4">
          {loading ? (
            <div className="rounded-2xl border border-emerald-100 bg-white p-8 text-center">
              <div className="inline-flex items-center gap-2 text-slate-500">
                <RefreshCcw className="animate-spin" size={16} />
                Memuat data...
              </div>
            </div>
          ) : filtered.length === 0 ? (
            <div className="rounded-2xl border border-emerald-100 bg-white p-8 text-center text-slate-400">
              Data tidak ditemukan
            </div>
          ) : (
            filtered.map((row, i) => (
              <motion.div
                key={row.id}
                initial={{ opacity: 0, y: 14 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: i * 0.03 }}
                className="relative rounded-2xl border border-emerald-100 bg-linear-to-br from-white to-emerald-50/40 p-4 shadow-sm"
              >
                {/* nomor row */}
                <div className="absolute top-3 right-3 h-8 min-w-8 px-2 rounded-full bg-emerald-600 text-white text-xs font-black flex items-center justify-center shadow">
                  #{i + 1}
                </div>

                <div className="flex items-start justify-between gap-3 pr-12">
                  <div>
                    <p className="text-xs text-slate-500">Kode</p>
                    <p className="font-black text-slate-800">
                      {row.code}
                    </p>
                  </div>

                  <span className={badgeType(row.type)}>
                    {row.type}
                  </span>
                </div>

                <div className="mt-4 space-y-3 text-sm">
                  <div>
                    <p className="text-xs text-slate-500">Nama</p>
                    <p className="font-semibold text-slate-700">
                      {row.name}
                    </p>
                  </div>

                  <div>
                    <p className="text-xs text-slate-500">Gudang</p>
                    <div className="flex items-center gap-2 mt-1">
                      <span className="flex h-8 w-8 items-center justify-center rounded-xl bg-emerald-100 text-emerald-700">
                        <Warehouse size={14} />
                      </span>

                      <span className="font-medium text-slate-700">
                        {row.warehouse_name}
                      </span>
                    </div>
                  </div>

                  <div className="flex items-center justify-between gap-3">
                    <div>
                      <p className="text-xs text-slate-500">Status</p>
                      <span className={badgeStatus(row.is_active)}>
                        {row.is_active ? "AKTIF" : "NONAKTIF"}
                      </span>
                    </div>

                    <div className="text-right">
                      <p className="text-xs text-slate-500">Dibuat</p>
                      <p className="font-medium text-slate-700">
                        {formatWIB(row.created_at)}
                      </p>
                    </div>
                  </div>
                </div>

                <div className="mt-4 grid grid-cols-2 gap-2">
                  <Link
                    href={`/location-bins/${row.id}`}
                    className="h-11 rounded-xl border border-sky-100 bg-white text-sky-600 flex items-center justify-center gap-2 shadow-sm"
                  >
                    <Eye size={16} />
                    Detail
                  </Link>

                  <Link
                    href={`/location-bins/${row.id}/edit`}
                    className="h-11 rounded-xl border border-amber-100 bg-white text-amber-600 flex items-center justify-center gap-2 shadow-sm"
                  >
                    <Pencil size={16} />
                    Edit
                  </Link>
                </div>
              </motion.div>
            ))
          )}
        </div>

        {/* ================= DESKTOP TABLE ================= */}
        <div className="hidden lg:block overflow-x-auto">
          <table className="w-full min-w-295 text-sm">
            <thead className="bg-linear-to-r from-emerald-50 via-lime-50 to-sky-50 text-slate-700">
              <tr>
                <th className="px-4 py-4 text-center font-bold w-16">
                  No
                </th>
                <th className="px-5 py-4 text-left font-bold">
                  Kode
                </th>
                <th className="px-5 py-4 text-left font-bold">
                  Nama
                </th>
                <th className="px-5 py-4 text-left font-bold">
                  Gudang
                </th>
                <th className="px-5 py-4 text-left font-bold">
                  Tipe
                </th>
                <th className="px-5 py-4 text-left font-bold">
                  Status
                </th>
                <th className="px-5 py-4 text-left font-bold">
                  Dibuat
                </th>
                <th className="px-5 py-4 text-center font-bold">
                  Aksi
                </th>
              </tr>
            </thead>

            <tbody>
              {loading ? (
                <tr>
                  <td
                    colSpan={8}
                    className="px-6 py-16 text-center"
                  >
                    <div className="inline-flex items-center gap-2 text-slate-500">
                      <RefreshCcw
                        className="animate-spin"
                        size={16}
                      />
                      Memuat data...
                    </div>
                  </td>
                </tr>
              ) : filtered.length === 0 ? (
                <tr>
                  <td
                    colSpan={8}
                    className="px-6 py-16 text-center text-slate-400"
                  >
                    Data tidak ditemukan
                  </td>
                </tr>
              ) : (
                filtered.map((row, i) => (
                  <motion.tr
                    key={row.id}
                    initial={{ opacity: 0, y: 12 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: i * 0.03 }}
                    className="border-t border-emerald-50 hover:bg-linear-to-r hover:from-emerald-50/60 hover:to-lime-50/40 transition"
                  >
                    {/* nomor row */}
                    <td className="px-4 py-4 text-center">
                      <span className="inline-flex h-8 min-w-8 px-2 items-center justify-center rounded-full bg-emerald-600 text-white text-xs font-black shadow">
                        {i + 1}
                      </span>
                    </td>

                    <td className="px-5 py-4 font-bold text-slate-800">
                      {row.code}
                    </td>

                    <td className="px-5 py-4">
                      {row.name}
                    </td>

                    <td className="px-5 py-4">
                      <div className="flex items-center gap-2">
                        <span className="flex h-8 w-8 items-center justify-center rounded-xl bg-emerald-100 text-emerald-700 shadow-sm">
                          <Warehouse size={15} />
                        </span>

                        {row.warehouse_name}
                      </div>
                    </td>

                    <td className="px-5 py-4">
                      <span className={badgeType(row.type)}>
                        {row.type}
                      </span>
                    </td>

                    <td className="px-5 py-4">
                      <span className={badgeStatus(row.is_active)}>
                        {row.is_active
                          ? "AKTIF"
                          : "NONAKTIF"}
                      </span>
                    </td>

                    <td className="px-5 py-4">
                      {formatWIB(row.created_at)}
                    </td>

                    <td className="px-5 py-4">
                      <div className="flex items-center justify-center gap-2">
                        <Link
                          href={`/location-bins/${row.id}`}
                          className="h-10 w-10 rounded-xl border border-sky-100 bg-white text-sky-600 flex items-center justify-center shadow hover:-translate-y-0.5 hover:shadow-md transition"
                        >
                          <Eye size={16} />
                        </Link>

                        <Link
                          href={`/location-bins/${row.id}/edit`}
                          className="h-10 w-10 rounded-xl border border-amber-100 bg-white text-amber-600 flex items-center justify-center shadow hover:-translate-y-0.5 hover:shadow-md transition"
                        >
                          <Pencil size={16} />
                        </Link>
                      </div>
                    </td>
                  </motion.tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </motion.div>
    </div>
  );
}

function GlassInput({ icon, ...props }: any) {
  return (
    <div className="relative">
      <div className="absolute inset-0 translate-y-1 bg-cyan-300/20 blur-lg rounded-2xl" />

      <div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 z-10">
        {icon}
      </div>

      <input
        {...props}
        className="relative w-full h-12 rounded-2xl bg-white/80 backdrop-blur-xl border border-white shadow-md pl-11 pr-4 outline-none focus:ring-2 focus:ring-cyan-400"
      />
    </div>
  );
}

function FilterSelect({ value, onChange, options }: any) {
  return (
    <div className="relative">
      <div className="absolute inset-0 translate-y-1 bg-cyan-300/20 blur-lg rounded-2xl" />

      <Select3D
        className="
        relative z-10 w-full
        [&>button]:w-full
        [&>button]:h-12
        [&>button]:rounded-2xl
        [&>button]:bg-white/85
        [&>button]:border
        [&>button]:border-white/70
        [&>button]:shadow-md
        [&>button]:font-medium
        [&>button]:text-slate-700
        "
        value={value}
        onChange={onChange}
        options={options}
      />
    </div>
  );
}

function Card({
  title,
  value,
  icon,
  gradient,
}: {
  title: string;
  value: number;
  icon: React.ReactNode;
  gradient: string;
}) {
  return (
    <motion.div
      whileHover={{ y: -4 }}
      className="relative rounded-3xl overflow-hidden"
    >
      <div className="absolute inset-0 translate-y-5 bg-cyan-300/10 blur-3xl rounded-3xl" />

      <div className="relative rounded-3xl bg-white/80 backdrop-blur-2xl border border-white/50 shadow-[0_18px_40px_rgba(0,0,0,0.10)] p-5">
        <div
          className={`absolute right-0 top-0 h-24 w-24 rounded-full bg-linear-to-br ${gradient} opacity-10 blur-2xl`}
        />

        <div className="relative flex items-center justify-between">
          <div>
            <p className="text-sm text-slate-500">{title}</p>
            <h3 className="text-4xl font-black text-slate-800 mt-2">
              {value}
            </h3>
          </div>

          <div
            className={`h-14 w-14 rounded-2xl bg-linear-to-br ${gradient} text-white flex items-center justify-center shadow-[0_12px_30px_rgba(0,0,0,0.15)]`}
          >
            {icon}
          </div>
        </div>
      </div>
    </motion.div>
  );
}