import Link from "next/link";
import { db } from "@/lib/db";
import { getOrgContext, canOrgModule, canOrgMutate } from "@/lib/org";
import { requireUser } from "@/lib/auth";
import { btn, Card, EmptyState, PageHeader, StatCard, StatusBadge, input, Badge } from "@/components/ui";
import { fmtDate, formatMoney } from "@/lib/utils";
import { approveVisitor, checkInVisitor } from "./actions";

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

const PAGE_SIZE = 25;

export default async function VisitorsPage({
  searchParams,
}: {
  searchParams: Promise<{ conf?: string; status?: string; checkin?: string; type?: string; q?: string; page?: string }>;
}) {
  await requireUser();
  const ctx = await getOrgContext();
  if (!ctx?.org || !canOrgModule(ctx.role, "visitors")) {
    return <EmptyState title="No access" body="Visitor management is not part of your role." />;
  }
  const org = ctx.org;
  const canMutate = canOrgMutate(ctx.role);
  const sp = await searchParams;
  const page = Math.max(1, parseInt(sp.page ?? "1", 10) || 1);

  const conferences = await db.conference.findMany({ where: { orgId: org.id }, orderBy: { startAt: "desc" }, select: { id: true, name: true } });
  const confFilter = sp.conf && conferences.some((c) => c.id === sp.conf) ? sp.conf : undefined;

  const where = {
    conference: { orgId: org.id },
    ...(confFilter ? { conferenceId: confFilter } : {}),
    ...(sp.status ? { status: sp.status } : {}),
    ...(sp.type ? { ticketType: { audience: sp.type } } : {}),
    ...(sp.checkin === "in" ? { checkIns: { some: { type: "CONFERENCE" } } } : {}),
    ...(sp.checkin === "out" ? { checkIns: { none: { type: "CONFERENCE" } } } : {}),
    ...(sp.q
      ? { OR: [{ name: { contains: sp.q } }, { email: { contains: sp.q } }, { organization: { contains: sp.q } }, { regCode: { contains: sp.q } }] }
      : {}),
  };

  const [total, rows, stats, checkedInCount, vipCount] = await Promise.all([
    db.registration.count({ where }),
    db.registration.findMany({
      where,
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
      include: {
        conference: { select: { id: true, name: true } },
        ticketType: { select: { name: true, audience: true } },
        checkIns: { where: { type: "CONFERENCE" }, select: { id: true } },
        certificates: { select: { id: true } },
      },
    }),
    db.registration.groupBy({ by: ["status"], where: { conference: { orgId: org.id } }, _count: true }),
    db.checkIn.count({ where: { type: "CONFERENCE", registration: { conference: { orgId: org.id } } } }),
    db.registration.count({ where: { conference: { orgId: org.id }, ticketType: { audience: "VIP" } } }),
  ]);
  const count = (s: string) => stats.find((x) => x.status === s)?._count ?? 0;
  const totalAll = stats.reduce((s, x) => s + x._count, 0);
  const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  const qs = (overrides: Record<string, string | undefined>) => {
    const p = new URLSearchParams();
    const merged = { conf: confFilter, status: sp.status, checkin: sp.checkin, type: sp.type, q: sp.q, ...overrides };
    for (const [k, v] of Object.entries(merged)) if (v) p.set(k, v);
    const s = p.toString();
    return `/dashboard/visitors${s ? `?${s}` : ""}`;
  };
  const exportQS = new URLSearchParams(Object.fromEntries(Object.entries({ conf: confFilter, status: sp.status, checkin: sp.checkin, type: sp.type, q: sp.q }).filter(([, v]) => v)) as Record<string, string>).toString();

  return (
    <main>
      <PageHeader
        title="👥 Visitors"
        sub={`Every attendee across ${org.name}'s conferences — search, filter, approve and check in.`}
        action={<a href={`/dashboard/visitors/export?${exportQS}`} className={btn.secondary}>⬇ Export CSV</a>}
      />

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
        <StatCard label="Total Visitors" value={totalAll} />
        <StatCard label="Confirmed" value={count("CONFIRMED")} accent="text-emerald-600" />
        <StatCard label="Pending" value={count("PENDING")} accent="text-amber-600" />
        <StatCard label="Cancelled" value={count("CANCELLED")} accent="text-red-500" />
        <StatCard label="Checked-in" value={checkedInCount} accent="text-sky-600" />
        <StatCard label="VIP" value={vipCount} accent="text-violet-600" />
      </div>

      {/* Filters */}
      <form className="mt-5 flex flex-wrap items-center gap-2" action="/dashboard/visitors">
        <input type="search" name="q" defaultValue={sp.q ?? ""} placeholder="Search name, email, org, code… 🔍" className={`${input} !w-64 !py-1.5 text-xs`} />
        <select name="conf" defaultValue={confFilter ?? ""} className={`${input} !w-56 !py-1.5 text-xs`} aria-label="Conference">
          <option value="">All conferences</option>
          {conferences.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>
        <select name="status" defaultValue={sp.status ?? ""} className={`${input} !w-36 !py-1.5 text-xs`} aria-label="Payment status">
          <option value="">Any status</option>
          <option value="CONFIRMED">Confirmed</option>
          <option value="PENDING">Pending</option>
          <option value="CANCELLED">Cancelled</option>
        </select>
        <select name="type" defaultValue={sp.type ?? ""} className={`${input} !w-36 !py-1.5 text-xs`} aria-label="Registration type">
          <option value="">Any type</option>
          {["ATTENDEE", "STUDENT", "VIP", "SPEAKER", "SPONSOR", "COMPLIMENTARY"].map((t) => (
            <option key={t} value={t}>{t[0] + t.slice(1).toLowerCase()}</option>
          ))}
        </select>
        <select name="checkin" defaultValue={sp.checkin ?? ""} className={`${input} !w-36 !py-1.5 text-xs`} aria-label="Check-in status">
          <option value="">Any check-in</option>
          <option value="in">Checked-in</option>
          <option value="out">Not checked-in</option>
        </select>
        <button className={btn.smSecondary}>Apply</button>
        {(sp.q || confFilter || sp.status || sp.type || sp.checkin) && (
          <Link href="/dashboard/visitors" className="text-xs text-zinc-500 hover:text-zinc-200">Clear ✕</Link>
        )}
      </form>

      {rows.length === 0 ? (
        <div className="mt-5"><EmptyState title="No visitors match these filters" /></div>
      ) : (
        <Card className="mt-5 overflow-x-auto">
          <table className="w-full min-w-[1000px] text-sm">
            <thead>
              <tr className="border-b border-zinc-800/60 text-left text-xs uppercase tracking-wider text-zinc-500">
                <th className="px-4 py-3">Visitor</th>
                <th className="px-3 py-3">Organization</th>
                <th className="px-3 py-3">Type</th>
                <th className="px-3 py-3">Conference</th>
                <th className="px-3 py-3">Registered</th>
                <th className="px-3 py-3">Amount</th>
                <th className="px-3 py-3">Payment</th>
                <th className="px-3 py-3">Check-in</th>
                <th className="px-3 py-3">Badge</th>
                <th className="px-3 py-3">Actions</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r) => (
                <tr key={r.id} className="border-b border-zinc-800/40 transition hover:bg-white/50">
                  <td className="px-4 py-3">
                    <div className="font-semibold text-zinc-100">{r.name}</div>
                    <div className="text-[11px] text-zinc-500">{r.email} · <span className="font-mono">{r.regCode}</span></div>
                  </td>
                  <td className="max-w-[140px] px-3 py-3">
                    <div className="truncate text-zinc-300">{r.organization ?? "—"}</div>
                    {r.designation && <div className="truncate text-[11px] text-zinc-500">{r.designation}</div>}
                  </td>
                  <td className="px-3 py-3">
                    <Badge className={r.ticketType.audience === "VIP" ? "bg-violet-500/15 text-violet-600" : "bg-slate-500/10 text-slate-600"}>
                      {r.ticketType.audience[0] + r.ticketType.audience.slice(1).toLowerCase()}
                    </Badge>
                  </td>
                  <td className="max-w-[150px] truncate px-3 py-3 text-zinc-400">{r.conference.name}</td>
                  <td className="whitespace-nowrap px-3 py-3 text-xs text-zinc-500">{fmtDate(r.createdAt)}</td>
                  <td className="px-3 py-3 tabular-nums text-zinc-300">{formatMoney(r.amount)}</td>
                  <td className="px-3 py-3"><StatusBadge status={r.status} /></td>
                  <td className="px-3 py-3">
                    {r.checkIns.length > 0
                      ? <Badge className="bg-emerald-500/15 text-emerald-600">✓ In</Badge>
                      : <Badge className="bg-zinc-500/10 text-zinc-500">—</Badge>}
                  </td>
                  <td className="px-3 py-3">
                    <Link href={`/ticket/${r.regCode}`} target="_blank" className="text-xs font-medium text-indigo-600 hover:underline">🎫 Badge</Link>
                  </td>
                  <td className="px-3 py-3">
                    <div className="flex items-center gap-1.5">
                      {canMutate && r.status === "PENDING" && (
                        <form action={approveVisitor.bind(null, r.id)}>
                          <button className={btn.sm}>Approve</button>
                        </form>
                      )}
                      {canMutate && r.status === "CONFIRMED" && r.checkIns.length === 0 && (
                        <form action={checkInVisitor.bind(null, r.id)}>
                          <button className={btn.smSecondary}>Check-in</button>
                        </form>
                      )}
                      <Link href={`/dashboard/c/${r.conference.id}/registrations`} className="rounded-lg px-2 py-1.5 text-xs text-zinc-500 transition hover:bg-white/70 hover:text-zinc-200" title="Open in conference">↗</Link>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {/* Pagination */}
      <div className="mt-4 flex items-center justify-between text-sm">
        <span className="text-xs text-zinc-500">
          Showing {(page - 1) * PAGE_SIZE + 1}–{Math.min(page * PAGE_SIZE, total)} of {total}
        </span>
        <div className="flex gap-2">
          {page > 1 && <Link href={qs({ page: String(page - 1) })} className={btn.smSecondary}>← Previous</Link>}
          {page < pages && <Link href={qs({ page: String(page + 1) })} className={btn.smSecondary}>Next →</Link>}
        </div>
      </div>
    </main>
  );
}
