"use client";

import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import Link from "next/link";
import { RefreshCcw, Plus } from "lucide-react";
import { UnitsTable } from "./UnitsTable";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Loading from "../components/Loading";


/* ================= TYPES ================= */
export type Unit = {
  id: number;
  code: string;
  name: string;
  category: string;
  symbol: string;
  is_base: boolean;
  is_active: boolean;
//   created_at: string;
//   updated_at: string;
  total_items: number;
};

export default function UnitsPage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const currentUser = session?.user as any;

  const [data, setData] = useState<Unit[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");

  const fetchData = async () => {
    setLoading(true);

    try {
      const res = await fetch(`/api/satuan?search=${search}`, {
        cache: "no-store",
      });

      const json = await res.json();
      setData(Array.isArray(json?.units) ? json.units : []);
    } catch (err) {
      console.error(err);
      setData([]);
    }

    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"];

    if (!allowedRoles.includes(currentUser?.role)) {
      router.replace("/");
      return;
    }
    fetchData();
  }, [search, status]);

   // 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 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative rounded-[28px] overflow-hidden"
      >
        <div className="absolute inset-0 bg-linear-to-br from-lime-300 via-green-200 to-emerald-300" />
        <div className="absolute inset-0 bg-white/30 backdrop-blur-2xl" />

        <div className="relative p-6 border border-white/40 bg-white/60 rounded-[28px]">

          <div className="flex flex-col md:flex-row md:justify-between gap-4">

            {/* TITLE */}
            <div>
              <h1 className="text-3xl font-bold text-green-900">
                📏 Master Units/Satuan
              </h1>
              <p className="text-sm text-green-800/70">
                Total unit: <b>{data?.length ?? 0}</b>
              </p>
            </div>

            {/* ACTIONS */}
            <div className="flex gap-2 items-center">

              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Cari unit..."
                className="px-4 py-2 rounded-xl border border-green-200"
              />

              <button
                onClick={fetchData}
                className="px-4 py-2 rounded-xl bg-green-600 text-white flex items-center gap-2"
              >
                <RefreshCcw size={16} />
                Refresh
              </button>

              <Link
                href="/satuan/tambah"
                className="px-4 py-2 rounded-xl bg-emerald-600 text-white flex items-center gap-2"
              >
                <Plus size={16} />
                Tambah
              </Link>

            </div>

          </div>
        </div>
      </motion.div>

      {/* TABLE */}
      {loading ? (
        <Loading pageName="Units"/>
      ) : (
        <UnitsTable data={data} />
      )}

    </div>
  );
}