import type { Metadata } from "next";
import Link from "next/link";
import { CategoryForm } from "@/components/admin/CategoryForm";
import { DeleteCategoryButton } from "@/components/admin/DeleteCategoryButton";
import { requireAdmin } from "@/lib/admin-actions";
import { db } from "@/lib/db";

export const metadata: Metadata = {
  title: "Manage Categories",
  description: "Admin category management.",
};

/** Category management: create form + list with game counts and delete guard. */
export default async function ManageCategoriesPage() {
  await requireAdmin();
  const categories = await db.category.findMany({
    orderBy: { name: "asc" },
    include: { _count: { select: { games: true } } },
  });

  return (
    <div>
      <h1 className="text-2xl font-bold text-white sm:text-3xl">Categories</h1>
      <p className="mt-1 text-sm text-slate-400">
        New categories appear across the site immediately. Deleting is blocked
        while games still use a category.
      </p>

      <section className="mt-6 max-w-2xl rounded-2xl border border-slate-800 bg-slate-900 p-5">
        <h2 className="mb-4 text-lg font-semibold text-white">Add category</h2>
        <CategoryForm submitLabel="Add category" />
      </section>

      <section className="mt-6 overflow-x-auto rounded-2xl border border-slate-800">
        <table className="w-full min-w-[560px] text-left text-sm">
          <thead>
            <tr className="border-b border-slate-800 text-xs tracking-wider text-slate-500 uppercase">
              <th scope="col" className="px-4 py-3">Name</th>
              <th scope="col" className="px-4 py-3">Slug</th>
              <th scope="col" className="px-4 py-3">Games</th>
              <th scope="col" className="px-4 py-3 text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-800">
            {categories.map((c) => (
              <tr key={c.id} className="bg-slate-900/40">
                <td className="px-4 py-3 font-medium text-white">{c.name}</td>
                <td className="px-4 py-3 font-mono text-xs text-slate-400">/{c.slug}</td>
                <td className="px-4 py-3 text-slate-300">{c._count.games}</td>
                <td className="px-4 py-3">
                  <div className="flex justify-end gap-2">
                    <Link
                      href={`/admin/categories/${c.id}/edit`}
                      className="rounded-lg border border-slate-700 px-3 py-1.5 text-xs font-semibold text-slate-200 hover:border-slate-500"
                    >
                      Edit
                    </Link>
                    <DeleteCategoryButton id={c.id} name={c.name} />
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </section>
    </div>
  );
}
