import { db } from "@/lib/db"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { formatPrice } from "@/lib/utils"
import { Plus } from "lucide-react"

export const metadata = { title: "Admin — Produits" }

export default async function AdminProductsPage() {
  const products = await db.product.findMany({
    include: { category: true, drop: true },
    orderBy: { createdAt: "desc" },
  })

  return (
    <div>
      <div className="flex items-center justify-between mb-8">
        <h1 className="text-2xl font-heading font-bold uppercase tracking-tight text-[var(--text)]">
          Produits
        </h1>
        <Button asChild size="sm">
          <Link href="/admin/products/new">
            <Plus size={14} />
            Nouveau produit
          </Link>
        </Button>
      </div>

      <div className="border border-[var(--border)] bg-[var(--surface)]">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-[var(--border)]">
              {["Nom", "Catégorie", "Drop", "Prix", "Stock", "Statut"].map((h) => (
                <th
                  key={h}
                  className="text-left px-4 py-3 font-mono text-xs uppercase tracking-widest text-[var(--text-muted)]"
                >
                  {h}
                </th>
              ))}
              <th className="px-4 py-3" />
            </tr>
          </thead>
          <tbody className="divide-y divide-[var(--border)]">
            {products.map((p) => (
              <tr key={p.id} className="hover:bg-[var(--surface-raised)] transition-colors">
                <td className="px-4 py-4 font-medium text-[var(--text)]">{p.name}</td>
                <td className="px-4 py-4 text-[var(--text-secondary)]">{p.category.name}</td>
                <td className="px-4 py-4 text-[var(--text-secondary)]">{p.drop?.name ?? "—"}</td>
                <td className="px-4 py-4 font-mono text-[var(--text)]">{formatPrice(p.price)}</td>
                <td className="px-4 py-4 font-mono">
                  <span className={p.stock === 0 ? "text-red-500" : "text-[var(--text)]"}>{p.stock}</span>
                </td>
                <td className="px-4 py-4">
                  <Badge variant={p.active ? "accent" : "outline"}>
                    {p.active ? "Actif" : "Inactif"}
                  </Badge>
                </td>
                <td className="px-4 py-4 text-right">
                  <Button asChild variant="ghost" size="sm">
                    <Link href={`/admin/products/${p.id}`}>Modifier</Link>
                  </Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {products.length === 0 && (
          <div className="py-16 text-center text-[var(--text-muted)]">
            Aucun produit. Commence par en créer un.
          </div>
        )}
      </div>
    </div>
  )
}
