import { notFound } from "next/navigation";
import QRCode from "qrcode";
import { db } from "@/lib/db";
import { getPublicConference } from "@/lib/conference";
import { dateRange, fmtTime, formatMoney } from "@/lib/utils";
import { StatusBadge } from "@/components/ui";
import Link from "next/link";
import { Confetti } from "@/components/fx";

export const metadata = { title: "Your ticket" };

export default async function TicketPage({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string; code: string }>;
  searchParams: Promise<{ new?: string; existing?: string }>;
}) {
  const { slug, code } = await params;
  const flags = await searchParams;
  const conf = await getPublicConference(slug);
  const registration = await db.registration.findUnique({
    where: { regCode: code },
    include: { ticketType: true, payments: { orderBy: { createdAt: "desc" } }, checkIns: { where: { type: "CONFERENCE" } } },
  });
  if (!registration || registration.conferenceId !== conf.id) notFound();

  const qr = await QRCode.toDataURL(registration.regCode, { width: 360, margin: 1, color: { dark: "#09090b", light: "#ffffff" } });
  const checkedIn = registration.checkIns.length > 0;

  return (
    <main className="mx-auto max-w-md px-4 py-10">
      {flags.new && <Confetti />}
      {flags.new && (
        <div className="mb-5 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-600">
          🎉 You’re registered! A confirmation email with this ticket has been sent to {registration.email}.
        </div>
      )}
      {flags.existing && (
        <div className="mb-5 rounded-lg border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm text-amber-600">
          You were already registered with this email — here’s your existing ticket.
        </div>
      )}

      <div className="fx-pop-in overflow-hidden rounded-2xl border border-zinc-800 bg-zinc-900 shadow-xl">
        <div className="px-6 py-5" style={{ background: `linear-gradient(135deg, ${conf.primaryColor}, ${conf.primaryColor}99)` }}>
          <div className="text-xs font-semibold uppercase tracking-widest text-white/70">Digital ticket</div>
          <div className="mt-1 text-lg font-bold text-white">{conf.name}</div>
          <div className="mt-0.5 text-sm text-white/80">
            {dateRange(conf.startAt, conf.endAt)} · {conf.type === "VIRTUAL" ? "Online" : conf.city}
          </div>
        </div>

        <div className="flex flex-col items-center border-b border-dashed border-zinc-700 px-6 py-6">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={qr} alt={`QR code for ${registration.regCode}`} className="h-44 w-44 rounded-lg bg-white p-2" />
          <div className="mt-3 font-mono text-lg font-bold tracking-widest text-zinc-100">{registration.regCode}</div>
          <div className="mt-1 text-xs text-zinc-500">Show this QR at the check-in desk</div>
        </div>

        <div className="space-y-2.5 px-6 py-5 text-sm">
          <Row k="Attendee" v={registration.name} />
          <Row k="Pass" v={`${registration.ticketType.name} · ${formatMoney(registration.amount)}`} />
          <Row k="Mode" v={registration.mode === "VIRTUAL" ? "Online" : "In person"} />
          <div className="flex items-center justify-between">
            <span className="text-zinc-500">Status</span>
            <span className="flex items-center gap-2">
              <StatusBadge status={registration.status} />
              {checkedIn && (
                <span className="inline-flex items-center rounded-full bg-emerald-500/10 px-2 py-0.5 text-[11px] font-semibold text-emerald-600">✓ CHECKED IN</span>
              )}
            </span>
          </div>
          {checkedIn && <div className="text-right text-xs text-emerald-600">Checked in {fmtTime(registration.checkIns[0].createdAt)}</div>}
          {conf.type !== "PHYSICAL" && registration.status === "CONFIRMED" && conf.streamUrl && (
            <div className="rounded-lg border border-zinc-800 bg-zinc-950 px-3 py-2.5">
              <div className="text-xs text-zinc-500">Online access</div>
              <a href={conf.streamUrl} target="_blank" rel="noreferrer" className="text-sm font-medium break-all hover:underline" style={{ color: conf.primaryColor }}>
                {conf.streamUrl}
              </a>
            </div>
          )}
        </div>
      </div>

      <div className="mt-5 flex justify-center gap-3 text-sm no-print">
        <Link href={`/c/${slug}/schedule`} className="text-zinc-400 hover:text-zinc-200">View schedule</Link>
        <span className="text-zinc-700">·</span>
        <Link href="/me" className="text-zinc-400 hover:text-zinc-200">My conferences</Link>
      </div>
    </main>
  );
}

function Row({ k, v }: { k: string; v: string }) {
  return (
    <div className="flex justify-between">
      <span className="text-zinc-500">{k}</span>
      <span className="font-medium text-zinc-200">{v}</span>
    </div>
  );
}
