import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import { AdminDeleteButton } from '@/components/admin/delete-button';
import type { Locale } from '@/i18n/config';

export default async function AdminCategoriesPage({ params: { locale } }: { params: { locale: Locale } }) {
  const categories = await prisma.category.findMany({
    orderBy: { order: 'asc' },
    include: { translations: { where: { locale: 'fr' } }, _count: { select: { products: true } } }
  });

  return (
    <div>
      <div className="flex items-center justify-between">
        <h1 className="font-display text-2xl font-semibold">Catégories</h1>
        <Link
          href={`/${locale}/admin/categories/new`}
          className="rounded-full bg-copper-500 px-4 py-2 text-sm font-semibold text-graphite-950"
        >
          + Nouvelle catégorie
        </Link>
      </div>

      <div className="mt-6 overflow-hidden rounded-2xl bg-white">
        <table className="w-full text-sm">
          <thead className="border-b border-graphite-800/10 text-graphite-900/50">
            <tr>
              <th className="px-4 py-3 text-start">Nom</th>
              <th className="px-4 py-3 text-start">Slug</th>
              <th className="px-4 py-3 text-start">Produits</th>
              <th className="px-4 py-3" />
            </tr>
          </thead>
          <tbody>
            {categories.map((c) => (
              <tr key={c.id} className="border-b border-graphite-800/5 last:border-0">
                <td className="px-4 py-3">{c.translations[0]?.name ?? c.slug}</td>
                <td className="px-4 py-3 text-graphite-900/60">{c.slug}</td>
                <td className="px-4 py-3 text-graphite-900/60">{c._count.products}</td>
                <td className="px-4 py-3 text-end">
                  <Link href={`/${locale}/admin/categories/${c.id}`} className="text-copper-600 hover:underline">
                    Modifier
                  </Link>
                  <AdminDeleteButton
                    apiPath={`/api/admin/categories/${c.id}`}
                    confirmMessage="Supprimer cette catégorie ?"
                  />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {categories.length === 0 && <p className="p-6 text-graphite-900/50">Aucune catégorie.</p>}
      </div>
    </div>
  );
}
