import { db } from "@/lib/db";
import { requireConfAccess } from "@/lib/rbac";
import { Card, PageHeader, StatCard, input } from "@/components/ui";
import { fmtTime } from "@/lib/utils";
import { checkInAction } from "../actions";

export const metadata = { title: "Check-in" };

const TONES: Record<string, string> = {
  ok: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600",
  warn: "border-amber-500/30 bg-amber-500/10 text-amber-600",
  error: "border-red-500/30 bg-red-500/10 text-red-600",
};

export default async function CheckinPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ msg?: string; tone?: string }>;
}) {
  const { id } = await params;
  const { msg, tone } = await searchParams;
  await requireConfAccess(id, "checkin.perform");

  const [confirmed, checkedIn, recent] = await Promise.all([
    db.registration.count({ where: { conferenceId: id, status: "CONFIRMED" } }),
    db.checkIn.count({ where: { type: "CONFERENCE", registration: { conferenceId: id } } }),
    db.checkIn.findMany({
      where: { type: "CONFERENCE", registration: { conferenceId: id } },
      orderBy: { createdAt: "desc" },
      take: 12,
      include: { registration: { include: { ticketType: true } } },
    }),
  ]);

  return (
    <main>
      <PageHeader title="Check-in desk" sub="Scan a QR ticket (scanners type the code + Enter) or enter the registration code manually." />

      <div className="grid gap-3 sm:grid-cols-3">
        <StatCard label="Checked in" value={checkedIn} accent="text-emerald-600" />
        <StatCard label="Confirmed registrations" value={confirmed} />
        <StatCard label="Attendance rate" value={confirmed ? `${Math.round((checkedIn / confirmed) * 100)}%` : "—"} />
      </div>

      {msg && <div className={`mt-4 rounded-lg border px-4 py-3 text-sm font-medium ${TONES[tone ?? "ok"]}`}>{msg}</div>}

      <Card className="mt-4 p-6">
        <form action={checkInAction.bind(null, id)} className="flex gap-3">
          <input
            name="code"
            required
            autoFocus
            autoComplete="off"
            placeholder="CFX-XXXXXX"
            className={`${input} font-mono text-lg uppercase tracking-widest`}
          />
          <button className="shrink-0 rounded-lg bg-emerald-600 px-6 text-sm font-semibold text-white transition hover:bg-emerald-500">
            Check in
          </button>
        </form>
        <p className="mt-2 text-xs text-zinc-600">The field keeps focus — a USB/Bluetooth QR scanner can check people in continuously.</p>
      </Card>

      <Card className="mt-4 p-5">
        <h2 className="text-sm font-semibold text-zinc-300">Recent check-ins</h2>
        <div className="mt-2 divide-y divide-zinc-800/70">
          {recent.length === 0 && <p className="py-3 text-sm text-zinc-500">Nobody checked in yet.</p>}
          {recent.map((c) => (
            <div key={c.id} className="flex items-center justify-between py-2 text-sm">
              <div>
                <span className="font-medium text-zinc-200">{c.registration.name}</span>
                <span className="ml-2 text-xs text-zinc-500">{c.registration.ticketType.name} · {c.registration.regCode}</span>
              </div>
              <span className="text-xs tabular-nums text-zinc-500">{fmtTime(c.createdAt)}{c.checkedInBy ? ` · by ${c.checkedInBy}` : ""}</span>
            </div>
          ))}
        </div>
      </Card>
    </main>
  );
}
