import QRCode from "qrcode";
import { headers } from "next/headers";
import { db } from "@/lib/db";
import { dateRange, fmtDate } from "@/lib/utils";
import { Logo } from "@/components/ui";
import Link from "next/link";

export const metadata = { title: "Certificate verification" };

export default async function VerifyPage({ params }: { params: Promise<{ certId: string }> }) {
  const { certId } = await params;
  const cert = await db.certificate.findUnique({
    where: { certId: certId.toUpperCase() },
    include: { conference: { include: { org: true } } },
  });

  if (!cert) {
    return (
      <main className="flex min-h-screen flex-col items-center justify-center bg-zinc-950 px-4 text-center">
        <div className="text-5xl">❌</div>
        <h1 className="mt-4 text-xl font-bold text-zinc-100">Certificate not found</h1>
        <p className="mt-2 max-w-sm text-sm text-zinc-500">
          No certificate with ID <span className="font-mono text-zinc-300">{certId}</span> exists. It may have been revoked or the ID was mistyped.
        </p>
        <Link href="/" className="mt-6 text-sm text-indigo-600 hover:underline">← Back to Confexe</Link>
      </main>
    );
  }

  const conf = cert.conference;
  const h = await headers();
  const host = h.get("x-forwarded-host") ?? h.get("host") ?? "localhost:3300";
  const proto = h.get("x-forwarded-proto") ?? (host.startsWith("localhost") ? "http" : "https");
  const verifyUrl = `${proto}://${host}/verify/${cert.certId}`;
  const qr = await QRCode.toDataURL(verifyUrl, { width: 200, margin: 1 });
  const typeLabel = cert.type.charAt(0) + cert.type.slice(1).toLowerCase();

  return (
    <main className="min-h-screen bg-zinc-950 px-4 py-10">
      <div className="mx-auto max-w-3xl">
        <div className="mb-6 flex items-center justify-between no-print">
          <Logo />
          <div className="fx-in fx-d2 flex items-center gap-2 rounded-full border border-emerald-500/30 bg-emerald-500/10 px-3 py-1.5 text-sm font-medium text-emerald-600">
            ✓ Verified authentic
          </div>
        </div>

        {/* Printable certificate */}
        <div className="fx-pop-in rounded-xl border-8 bg-white p-10 text-center text-slate-900 shadow-2xl" style={{ borderColor: conf.primaryColor }}>
          <div className="text-xs font-semibold uppercase tracking-[0.3em]" style={{ color: conf.primaryColor }}>
            Certificate of {typeLabel}
          </div>
          <div className="mt-6 text-sm text-slate-500">This is to certify that</div>
          <div className="mt-2 font-serif text-4xl font-bold">{cert.recipientName}</div>
          <div className="mx-auto mt-3 h-px w-48" style={{ background: conf.primaryColor }} />
          <div className="mx-auto mt-5 max-w-xl text-[15px] leading-relaxed text-slate-600">
            {cert.type === "SPEAKER" || cert.type === "PRESENTER"
              ? `delivered a presentation at`
              : cert.type === "VOLUNTEER"
              ? `served as a volunteer at`
              : cert.type === "REVIEWER"
              ? `served as a reviewer for`
              : cert.type === "ORGANIZER"
              ? `served on the organizing committee of`
              : `participated in`}{" "}
            <span className="font-semibold text-slate-800">{conf.name}</span>, held{" "}
            {dateRange(conf.startAt, conf.endAt)}
            {conf.city ? ` in ${conf.city}` : ""}, organized by {conf.org.name}.
          </div>
          <div className="mt-10 flex items-end justify-between text-left">
            <div className="text-xs text-slate-500">
              <div className="font-mono font-semibold text-slate-700">{cert.certId}</div>
              <div className="mt-1">Issued {fmtDate(cert.issuedAt)}</div>
              <div className="mt-0.5">Verify: {verifyUrl}</div>
            </div>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={qr} alt="Verification QR" className="h-20 w-20" />
          </div>
        </div>

        <div className="mt-6 rounded-xl border border-zinc-800 bg-zinc-900/60 p-5 text-sm no-print">
          <h2 className="font-semibold text-zinc-200">Verification details</h2>
          <dl className="mt-3 grid gap-x-8 gap-y-2 sm:grid-cols-2">
            {[
              ["Certificate ID", cert.certId],
              ["Recipient", cert.recipientName],
              ["Type", typeLabel],
              ["Conference", conf.name],
              ["Organizer", conf.org.name],
              ["Issued", fmtDate(cert.issuedAt)],
            ].map(([k, v]) => (
              <div key={k} className="flex justify-between gap-4 border-b border-zinc-800/60 pb-1.5">
                <dt className="text-zinc-500">{k}</dt>
                <dd className="font-medium text-zinc-200">{v}</dd>
              </div>
            ))}
          </dl>
          <p className="mt-4 text-xs text-zinc-600">
            This certificate was digitally issued via Confexe. Anyone with this URL or the QR code can verify its authenticity.
          </p>
        </div>
      </div>
    </main>
  );
}
