"use client";

import { motion } from "framer-motion";
import type { Unit } from "./page";
import { Pencil, Trash2 } from "lucide-react";
import Link from "next/link";
import { useSession } from "next-auth/react";

/* ================= TABLE ================= */
export function UnitsTable({ data }: { data: Unit[] }) {

  const { data: session, status } = useSession();
  const currentUser = session?.user as any;
  const allowedRoles = ["ADMIN", "OPERATOR", "SUPERVISOR"];

  const handleDelete = async (id: number) => {
    if (!allowedRoles.includes(currentUser?.role)) {
      // router.replace("/satuan");
      return;
    }

    const ok = confirm("Yakin mau hapus unit ini?");
    if (!ok) return;

    try {
      const res = await fetch(`/api/satuan/${id}`, {
        method: "DELETE",
      });

      const json = await res.json();

      if (!res.ok) {
        alert(json.message || "Gagal menghapus unit");
        return;
      }

      alert("Unit berhasil dihapus");
      location.reload();
    } catch (err) {
      console.error(err);
      alert("Terjadi error saat menghapus");
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.98 }}
      animate={{ opacity: 1, scale: 1 }}
      className="rounded-3xl bg-white/80 backdrop-blur-xl shadow-xl overflow-hidden"
    >
      <div className="overflow-x-auto">

        <table className="w-full text-sm border-collapse">

          {/* HEADER */}
          <thead className="bg-gradient-to-r from-green-50 via-emerald-50 to-lime-50 text-green-900">
            <tr className="text-left">

              <th className="p-4 w-12 font-semibold">#</th>
              <th className="p-4 font-semibold">Code</th>
              <th className="p-4 font-semibold">Name</th>
              <th className="p-4 font-semibold">Category</th>
              <th className="p-4 font-semibold">Symbol</th>
              <th className="p-4 font-semibold text-center">Base</th>
              <th className="p-4 font-semibold text-center">Status</th>
              <th className="p-4 font-semibold text-center">Items</th>
              <th className="p-4 font-semibold text-center">Action</th>

            </tr>
          </thead>

          {/* BODY */}
          <tbody className="text-gray-700">

            {data?.length === 0 ? (
              <tr>
                <td colSpan={9} className="p-12 text-center text-gray-400">
                  🌱 No units found
                </td>
              </tr>
            ) : (
              data.map((u, i) => (
                <motion.tr
                  key={u.id}
                  initial={{ opacity: 0, y: 8 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: i * 0.02 }}
                  className="border-t border-green-100/60 hover:bg-green-50/60 transition"
                >

                  {/* NO */}
                  <td className="p-4 text-gray-500 align-middle">
                    {i + 1}
                  </td>

                  {/* CODE */}
                  <td className="p-4 font-bold text-green-800 align-middle tracking-wide">
                    {u.code}
                  </td>

                  {/* NAME */}
                  <td className="p-4 align-middle">
                    <div className="font-medium text-gray-800 leading-snug">
                      {u.name}
                    </div>
                  </td>

                  {/* CATEGORY */}
                  <td className="p-4 text-gray-600 align-middle">
                    {u.category || "-"}
                  </td>

                  {/* SYMBOL */}
                  <td className="p-4 align-middle">
                    <span className="text-gray-700">
                      {u.symbol || "-"}
                    </span>
                  </td>

                  {/* BASE */}
                  <td className="p-4 text-center align-middle">
                    {u.is_base ? (
                      <span className="text-green-600 font-semibold">
                        ✔
                      </span>
                    ) : (
                      <span className="text-gray-400">—</span>
                    )}
                  </td>

                  {/* STATUS */}
                  <td className="p-4 text-center align-middle">
                    <span
                      className={`px-3 py-1 rounded-full text-xs font-medium whitespace-nowrap ${
                        u.is_active
                          ? "bg-green-100 text-green-700"
                          : "bg-gray-200 text-gray-500"
                      }`}
                    >
                      {u.is_active ? "Active" : "Inactive"}
                    </span>
                  </td>

                  {/* ITEMS */}
                  <td className="p-4 text-center align-middle">
                    <span className="px-3 py-1 rounded-full bg-emerald-100 text-emerald-700 font-medium whitespace-nowrap">
                      {u.total_items}
                    </span>
                  </td>

                  {/* ACTIONS */}
                  <td className="p-4 align-middle">
                    <div className="flex justify-center items-center gap-2">

                      {/* EDIT */}
                      <Link
                        href={`/satuan/${u.id}`}
                        className="flex items-center gap-1 px-3 py-1.5
                        rounded-lg bg-white border border-green-200
                        text-green-800 text-xs font-medium
                        hover:shadow-md hover:scale-105 transition
                        whitespace-nowrap"
                      >
                        <Pencil size={14} />
                        Edit
                      </Link>

                      {/* DELETE */}
                      <button
                        onClick={() => handleDelete(u.id)}
                        className="flex items-center gap-1 px-3 py-1.5
                        rounded-lg bg-red-50 border border-red-200
                        text-red-600 text-xs font-medium
                        hover:shadow-md hover:scale-105 transition
                        whitespace-nowrap"
                      >
                        <Trash2 size={14} />
                        Hapus
                      </button>

                    </div>
                  </td>

                </motion.tr>
              ))
            )}

          </tbody>

        </table>

      </div>
    </motion.div>
  );
}