import Link from "next/link";
import { db } from "@/lib/db";
import { requireSuperAdmin } from "@/lib/auth";
import { Card, PageHeader, StatusBadge, btn } from "@/components/ui";
import { dateRange, formatMoney } from "@/lib/utils";
import { adminDeleteConference, adminSetConferenceStatus } from "../actions";

export const metadata = { title: "Conference management" };

export default async function AdminConferencesPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  await requireSuperAdmin();
  const { error } = await searchParams;
  const conferences = await db.conference.findMany({
    orderBy: { startAt: "desc" },
    include: {
      org: true,
      _count: { select: { registrations: { where: { status: "CONFIRMED" } }, sessions: true, speakers: true } },
      registrations: { where: { status: "CONFIRMED" }, select: { amount: true } },
    },
  });

  return (
    <div>
      <PageHeader
        title="Conference management"
        sub={`${conferences.length} conferences across all organizations`}
        action={<Link href="/dashboard/conferences/new" className={btn.primary}>+ New conference</Link>}
      />
      {error && <div className="mb-4 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-600">{error}</div>}

      <div className="space-y-3">
        {conferences.map((c) => {
          const revenue = c.registrations.reduce((s, r) => s + r.amount, 0);
          const nextActions: [string, string][] =
            c.status === "DRAFT" ? [["PUBLISHED", "Publish"]]
            : c.status === "PUBLISHED" ? [["LIVE", "Go live"], ["ARCHIVED", "Archive"]]
            : c.status === "LIVE" ? [["COMPLETED", "Complete"]]
            : c.status === "COMPLETED" ? [["ARCHIVED", "Archive"]]
            : [["DRAFT", "Restore to draft"]];
          return (
            <Card key={c.id} className="p-5">
              <div className="flex flex-wrap items-center justify-between gap-4">
                <div className="flex min-w-0 items-center gap-4">
                  <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-lg font-bold text-white shadow-md" style={{ background: c.primaryColor }}>
                    {c.name[0]}
                  </span>
                  <div className="min-w-0">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="truncate font-bold text-zinc-100">{c.name}</span>
                      <StatusBadge status={c.status} />
                    </div>
                    <div className="mt-0.5 text-sm text-zinc-500">
                      {c.org.name} · {dateRange(c.startAt, c.endAt)} · {c.type}
                    </div>
                  </div>
                </div>
                <div className="flex gap-5 text-center text-sm">
                  <div><div className="font-bold tabular-nums text-zinc-200">{c._count.registrations}</div><div className="text-[11px] text-zinc-500">registered</div></div>
                  <div><div className="font-bold tabular-nums text-zinc-200">{c._count.sessions}</div><div className="text-[11px] text-zinc-500">sessions</div></div>
                  <div><div className="font-bold tabular-nums text-zinc-200">{c._count.speakers}</div><div className="text-[11px] text-zinc-500">speakers</div></div>
                  <div><div className="font-bold tabular-nums text-emerald-600">{formatMoney(revenue)}</div><div className="text-[11px] text-zinc-500">revenue</div></div>
                </div>
              </div>
              <div className="mt-4 flex flex-wrap items-center gap-2 border-t border-zinc-800/60 pt-3">
                <Link href={`/dashboard/c/${c.id}`} className={btn.sm}>Open workspace</Link>
                <Link href={`/c/${c.slug}`} target="_blank" className={btn.smSecondary}>Public site ↗</Link>
                {nextActions.map(([status, label]) => (
                  <form key={status} action={adminSetConferenceStatus.bind(null, c.id, status)}>
                    <button className={btn.smSecondary}>{label}</button>
                  </form>
                ))}
                <details className="ml-auto">
                  <summary className="cursor-pointer list-none rounded-lg px-2.5 py-1.5 text-xs font-medium text-red-600/80 transition hover:bg-red-500/10 hover:text-red-600 [&::-webkit-details-marker]:hidden">
                    Delete…
                  </summary>
                  <form action={adminDeleteConference.bind(null, c.id)} className="absolute z-10 mt-1 flex items-center gap-2 rounded-xl border border-red-200 bg-white/95 p-3 shadow-xl backdrop-blur">
                    <span className="text-xs text-zinc-500">Permanently deletes <strong>{c.name}</strong> with all registrations, sessions and certificates.</span>
                    <button className="shrink-0 rounded-lg bg-red-500 px-3 py-1.5 text-xs font-bold text-white hover:bg-red-600">Yes, delete</button>
                  </form>
                </details>
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
}
