import Link from "next/link";
import { db } from "@/lib/db";
import { can, requireConfAccess } from "@/lib/rbac";
import { PageHeader, StatusBadge, btn, input } from "@/components/ui";
import { fmtDateTime, formatMoney } from "@/lib/utils";
import { setRegistrationStatus } from "../actions";

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

export default async function RegistrationsPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ q?: string; status?: string }>;
}) {
  const { id } = await params;
  const { q, status } = await searchParams;
  const { membership } = await requireConfAccess(id, "registrations.manage");
  const conf = await db.conference.findUnique({ where: { id }, select: { slug: true } });

  const regs = await db.registration.findMany({
    where: {
      conferenceId: id,
      ...(status ? { status } : {}),
      ...(q ? { OR: [{ name: { contains: q } }, { email: { contains: q } }, { regCode: { contains: q.toUpperCase() } }, { organization: { contains: q } }] } : {}),
    },
    orderBy: { createdAt: "desc" },
    include: { ticketType: true, checkIns: { where: { type: "CONFERENCE" } } },
  });

  return (
    <main>
      <PageHeader
        title="Registrations"
        sub={`${regs.length} shown`}
        action={can(membership, "registrations.export") ? <a href={`/api/v1/conferences/${id}/registrations.csv`} className={btn.secondary}>⬇ Export CSV</a> : undefined}
      />

      <form className="mb-4 flex flex-wrap gap-2">
        <input name="q" defaultValue={q} placeholder="Search name, email, code, org…" className={`${input} max-w-xs`} />
        <select name="status" defaultValue={status ?? ""} className={`${input} w-40`}>
          <option value="">All statuses</option>
          <option value="CONFIRMED">Confirmed</option>
          <option value="PENDING">Pending</option>
          <option value="CANCELLED">Cancelled</option>
        </select>
        <button className={btn.secondary}>Filter</button>
      </form>

      <div className="overflow-x-auto rounded-xl border border-zinc-800">
        <table className="w-full min-w-[760px] 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">Attendee</th>
              <th className="px-4 py-3">Code</th>
              <th className="px-4 py-3">Pass</th>
              <th className="px-4 py-3">Mode</th>
              <th className="px-4 py-3">Amount</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3">Registered</th>
              <th className="px-4 py-3 text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-zinc-800/70">
            {regs.length === 0 && (
              <tr><td colSpan={8} className="px-4 py-10 text-center text-zinc-500">No registrations match.</td></tr>
            )}
            {regs.map((r) => (
              <tr key={r.id} className="hover:bg-zinc-900/40">
                <td className="px-4 py-2.5">
                  <div className="font-medium text-zinc-200">{r.name}</div>
                  <div className="text-xs text-zinc-500">{r.email}{r.organization ? ` · ${r.organization}` : ""}</div>
                </td>
                <td className="px-4 py-2.5">
                  <Link href={`/c/${conf?.slug}/ticket/${r.regCode}`} target="_blank" className="font-mono text-xs text-indigo-600 hover:underline">{r.regCode}</Link>
                </td>
                <td className="px-4 py-2.5 text-zinc-400">{r.ticketType.name}</td>
                <td className="px-4 py-2.5 text-xs text-zinc-500">{r.mode === "VIRTUAL" ? "🖥️ Virtual" : "🏛️ In person"}</td>
                <td className="px-4 py-2.5 tabular-nums text-zinc-300">{formatMoney(r.amount)}</td>
                <td className="px-4 py-2.5">
                  <div className="flex items-center gap-1.5">
                    <StatusBadge status={r.status} />
                    {r.checkIns.length > 0 && <span title="Checked in">✅</span>}
                  </div>
                </td>
                <td className="px-4 py-2.5 text-xs text-zinc-500">{fmtDateTime(r.createdAt)}</td>
                <td className="px-4 py-2.5 text-right">
                  <div className="flex justify-end gap-1.5">
                    {r.status === "PENDING" && (
                      <form action={setRegistrationStatus.bind(null, id, r.id, "CONFIRMED")}>
                        <button className={btn.sm}>Confirm</button>
                      </form>
                    )}
                    {r.status !== "CANCELLED" && (
                      <form action={setRegistrationStatus.bind(null, id, r.id, "CANCELLED")}>
                        <button className={btn.smSecondary}>Cancel</button>
                      </form>
                    )}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </main>
  );
}
