"use client";

import { motion } from "framer-motion";
import Link from "next/link";
import { Pencil, Trash2 } from "lucide-react";
import { useSession } from "next-auth/react";

export function CategoriesTable({ isAdmin, data, page, limit }: any) {

  // const { data: session, status } = useSession();
  // const currentUser = session?.user as any;
  // const allowedRoles = ["ADMIN"];

const handleDelete = async (id: number) => {
   if (!isAdmin) {
      // router.replace("/satuan");
      return;
    }
  const ok = confirm("Yakin mau hapus kategori ini?");
    if (!ok) return;

    try {
          const res = await fetch(`/api/categories/${id}`, {
          method: "DELETE",
          });

          const json = await res.json();

          if (!res.ok) {
          alert(json.message || "Gagal hapus kategori");
          return;
          }

          alert("Kategori berhasil dihapus");

          location.reload(); // masih boleh kalau mau simple
      } catch (err) {
          console.log(err);
          alert("Terjadi error saat menghapus");
      }
    };

      // optional safety (biar tidak flash UI)
  // if (!session) return null;
  
  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.98 }}
      animate={{ opacity: 1, scale: 1 }}
      className="relative rounded-3xl p-px
      bg-linear-to-br from-green-200/40 via-emerald-200/20 to-transparent"
    >
      {/* DEPTH */}
      <div className="absolute inset-0 translate-y-6 bg-green-300/20 blur-3xl rounded-3xl" />

      <div className="relative rounded-3xl
      bg-white/85 backdrop-blur-2xl
      border border-white/40
      shadow-[0_20px_60px_rgba(0,0,0,0.15)]
      overflow-hidden">

        <div className="overflow-x-auto">
          <table className="w-full text-sm">

            {/* HEADER */}
            <thead className="bg-linear-to-r from-green-50 via-emerald-50 to-lime-50 text-gray-600">
              <tr>
                <th className="p-4 text-left w-17.5">No</th>
                <th className="p-4 text-left">Kategori</th>
                <th className="p-4 text-left">Deskripsi</th>
                <th className="p-4 text-center w-35">Status</th>
                <th className="p-4 text-center w-35">Action</th>
              </tr>
            </thead>

            {/* BODY */}
            <tbody>
              {data.length === 0 ? (
                <tr>
                  <td colSpan={5} className="text-center p-8 text-gray-400">
                    🌱 Belum ada kategori
                  </td>
                </tr>
              ) : (
                data.map((c: any, i: number) => {
                  const no = (page - 1) * limit + i + 1;

                  return (
                    <motion.tr
                      key={c.id}
                      initial={{ opacity: 0, y: 12 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: i * 0.03 }}
                      className="border-t border-green-100/60
                      hover:bg-linear-to-r hover:from-green-50/70 hover:to-emerald-50/40
                      transition"
                    >
                      {/* NO */}
                      <td className="p-4 text-gray-500">{no}</td>

                      {/* NAME */}
                      <td className="p-4">
                        <div className="flex flex-col">
                          <span className="font-semibold text-green-900">
                                🌿 {c.name}
                                </span>
                                <span className="text-xs text-green-700/60 flex items-center gap-1">
                                Category • <span className="font-bold">{c.total_items}</span> item
                            </span>
                        </div>
                      </td>

                      {/* DESC */}
                      <td className="p-4 text-gray-600">
                        {c.description || (
                          <span className="text-gray-400 italic">
                            Tidak ada deskripsi
                          </span>
                        )}
                      </td>

                      {/* STATUS */}
                      <td className="p-4 text-center">
                        <span
                          className={`px-3 py-1 rounded-full text-xs font-medium shadow-sm
                          ${
                            c.is_active
                              ? "bg-green-100 text-green-700 shadow-green-200/50"
                              : "bg-gray-200 text-gray-500"
                          }`}
                        >
                          {c.is_active ? "🌱 Active" : "Inactive"}
                        </span>
                      </td>

                      {/* ACTION */}
                      <td className="p-4">
                          {isAdmin && (
                                <div className="flex justify-center gap-2">
                                  {/* EDIT */}
                                  <Link
                                    href={`/categories/${c.id}`}
                                    className="flex items-center gap-1 px-3 py-1.5
                                    rounded-lg bg-white/80 border border-green-200
                                    shadow-sm hover:shadow-md hover:scale-105
                                    transition text-green-800 text-xs font-medium"
                                  >
                                    <Pencil size={14} />
                                    Edit
                                  </Link>

                                  {/* DELETE */}
                                  <button
                                    onClick={() => handleDelete(c.id)}
                                    className="flex items-center gap-1 px-3 py-1.5
                                    rounded-lg bg-red-50 border border-red-200
                                    shadow-sm hover:shadow-md hover:scale-105
                                    transition text-red-600 text-xs font-medium"
                                  >
                                    <Trash2 size={14} />
                                    Hapus
                                  </button>

                                </div>
                          )}
               
                      </td>

                    </motion.tr>
                  );
                })
              )}
            </tbody>

          </table>
        </div>
      </div>
    </motion.div>
  );
}