import Link from "next/link";
import { db } from "@/lib/db";
import { requireConfAccess } from "@/lib/rbac";
import { Card, PageHeader, btn, input, Field, Badge } from "@/components/ui";
import { fmtDate } from "@/lib/utils";
import { generateCertificates } from "../actions";

export const metadata = { title: "Certificates" };

export default async function CertificatesPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ generated?: string }>;
}) {
  const { id } = await params;
  const { generated } = await searchParams;
  await requireConfAccess(id, "certificates.manage");
  const certs = await db.certificate.findMany({
    where: { conferenceId: id },
    orderBy: { issuedAt: "desc" },
  });

  return (
    <main>
      <PageHeader title="Certificates" sub="Each certificate gets a unique ID and a public verification URL with QR." />
      {generated && (
        <div className="mb-4 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-600">
          Generated {generated} new certificate{generated === "1" ? "" : "s"}. Recipients with accounts see them under My Conferences.
        </div>
      )}

      <div className="grid gap-6 lg:grid-cols-3">
        <div className="lg:col-span-2">
          <div className="overflow-x-auto rounded-xl border border-zinc-800">
            <table className="w-full min-w-[560px] text-sm">
              <thead>
                <tr className="border-b border-zinc-800 bg-zinc-900/60 text-left text-xs uppercase tracking-wider text-zinc-500">
                  <th className="px-4 py-3">Certificate ID</th>
                  <th className="px-4 py-3">Recipient</th>
                  <th className="px-4 py-3">Type</th>
                  <th className="px-4 py-3">Issued</th>
                  <th className="px-4 py-3 text-right">Verify</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-zinc-800/70">
                {certs.length === 0 && (
                  <tr><td colSpan={5} className="px-4 py-10 text-center text-zinc-500">No certificates issued yet.</td></tr>
                )}
                {certs.map((c) => (
                  <tr key={c.id} className="hover:bg-zinc-900/40">
                    <td className="px-4 py-2.5 font-mono text-xs text-zinc-300">{c.certId}</td>
                    <td className="px-4 py-2.5">
                      <div className="font-medium text-zinc-200">{c.recipientName}</div>
                      <div className="text-xs text-zinc-500">{c.recipientEmail}</div>
                    </td>
                    <td className="px-4 py-2.5"><Badge className="bg-violet-500/10 text-violet-600">{c.type}</Badge></td>
                    <td className="px-4 py-2.5 text-xs text-zinc-500">{fmtDate(c.issuedAt)}</td>
                    <td className="px-4 py-2.5 text-right">
                      <Link href={`/verify/${c.certId}`} target="_blank" className="text-xs font-medium text-indigo-600 hover:underline">Open ↗</Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <Card className="h-fit p-5">
          <h2 className="text-sm font-semibold text-zinc-200">Generate certificates</h2>
          <p className="mt-1 text-xs text-zinc-500">Idempotent — recipients who already have one of the chosen type are skipped.</p>
          <form action={generateCertificates.bind(null, id)} className="mt-4 space-y-3">
            <Field name="type" title="Certificate type">
              <select id="type" name="type" className={input} defaultValue="PARTICIPATION">
                <option value="PARTICIPATION">Participation (attendees)</option>
                <option value="SPEAKER">Speaker</option>
                <option value="VOLUNTEER">Volunteer</option>
                <option value="ORGANIZER">Organizer</option>
              </select>
            </Field>
            <Field name="scope" title="Attendee scope">
              <select id="scope" name="scope" className={input} defaultValue="CHECKED_IN">
                <option value="CHECKED_IN">Checked-in attendees only</option>
                <option value="CONFIRMED">All confirmed registrations</option>
              </select>
            </Field>
            <button className={`${btn.primary} w-full`}>Generate</button>
          </form>
        </Card>
      </div>
    </main>
  );
}
