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, StatusBadge, input } from "@/components/ui";
import { dateRange, fmtDate, formatMoney } from "@/lib/utils";
import { duplicateConference } from "@/app/dashboard/c/[id]/actions";
import { orgDeleteConference, orgSetConferenceStatus } from "./actions";

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

const FILTERS: { key: string; label: string }[] = [
  { key: "all", label: "All" },
  { key: "draft", label: "Drafts" },
  { key: "upcoming", label: "Upcoming" },
  { key: "ongoing", label: "Ongoing" },
  { key: "completed", label: "Completed" },
  { key: "archived", label: "Archived" },
];

export default async function ConferencesPage({
  searchParams,
}: {
  searchParams: Promise<{ f?: string; q?: string }>;
}) {
  await requireUser();
  const ctx = await getOrgContext();
  if (!ctx?.org || !canOrgModule(ctx.role, "conferences")) {
    return <EmptyState title="No access" body="Conference management is not part of your role." />;
  }
  const org = ctx.org;
  const canMutate = canOrgMutate(ctx.role);
  const canDelete = ["OWNER", "ADMIN"].includes(ctx.role);
  const { f = "all", q = "" } = await searchParams;
  const now = new Date();

  const all = await db.conference.findMany({
    where: {
      orgId: org.id,
      ...(q ? { name: { contains: q } } : {}),
    },
    orderBy: { startAt: "desc" },
    include: {
      _count: { select: { registrations: { where: { status: "CONFIRMED" } }, speakers: true, sponsors: true } },
      registrations: { where: { status: "CONFIRMED" }, select: { amount: true } },
    },
  });

  const rows = all.filter((c) => matchesWith(c, f, now));
  const countFor = (key: string) => all.filter((c) => (key === "all" ? true : matchesWith(c, key, now))).length;

  return (
    <main>
      <PageHeader
        title="📅 Conferences"
        sub={`Every conference run by ${org.name} — manage, publish, duplicate or archive from one place.`}
        action={canMutate ? (
          <div className="flex gap-2">
            <Link href="/dashboard/conferences/wizard" className={btn.primary}>⚡ Assisted wizard</Link>
            <Link href="/dashboard/conferences/new" className={btn.secondary}>+ Full form</Link>
          </div>
        ) : undefined}
      />

      <div className="mb-4 flex flex-wrap items-center gap-2">
        {FILTERS.map((t) => (
          <Link
            key={t.key}
            href={t.key === "all" ? "/dashboard/conferences" : `/dashboard/conferences?f=${t.key}`}
            className={`rounded-full px-3 py-1 text-xs font-semibold transition ${
              f === t.key ? "bg-indigo-500 text-white shadow-md shadow-indigo-500/30" : "border border-white/70 bg-white/50 text-zinc-400 hover:text-zinc-100"
            }`}
          >
            {t.label} <span className="opacity-70">({countFor(t.key)})</span>
          </Link>
        ))}
        <form className="ml-auto" action="/dashboard/conferences">
          {f !== "all" && <input type="hidden" name="f" value={f} />}
          <input type="search" name="q" defaultValue={q} placeholder="Search conferences… 🔍" className={`${input} !w-60 !py-1.5 text-xs`} />
        </form>
      </div>

      {rows.length === 0 ? (
        <EmptyState
          title={q ? `No conferences matching “${q}”` : "No conferences in this view"}
          body="Try a different filter, or create a new conference."
          action={canMutate ? <Link href="/dashboard/conferences/new" className={btn.primary}>Add New Conference</Link> : undefined}
        />
      ) : (
        <Card className="overflow-x-auto">
          <table className="w-full min-w-[980px] 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">Conference</th>
                <th className="px-3 py-3">Date</th>
                <th className="px-3 py-3">Location</th>
                <th className="px-3 py-3">Status</th>
                <th className="px-3 py-3">Regs</th>
                <th className="px-3 py-3">Speakers</th>
                <th className="px-3 py-3">Sponsors</th>
                <th className="px-3 py-3">Revenue</th>
                <th className="px-3 py-3">Created</th>
                <th className="px-3 py-3">Actions</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((c) => (
                <tr key={c.id} className="border-b border-zinc-800/40 align-middle transition hover:bg-white/50">
                  <td className="px-4 py-3">
                    <Link href={`/dashboard/c/${c.id}`} className="flex items-center gap-2.5 font-semibold text-zinc-100 hover:text-indigo-700">
                      <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-xs font-bold text-white" style={{ background: c.primaryColor }}>{c.name[0]}</span>
                      <span className="max-w-[210px]">
                        <span className="block truncate">{c.name}</span>
                        <span className="block text-[10px] font-normal text-zinc-500">#{c.id.slice(-8).toUpperCase()}</span>
                      </span>
                    </Link>
                  </td>
                  <td className="whitespace-nowrap px-3 py-3 text-zinc-400">{dateRange(c.startAt, c.endAt)}</td>
                  <td className="max-w-[130px] truncate px-3 py-3 text-zinc-400">{[c.city, c.state].filter(Boolean).join(", ") || "—"}</td>
                  <td className="px-3 py-3"><StatusBadge status={c.status} /></td>
                  <td className="px-3 py-3 tabular-nums text-zinc-300">{c._count.registrations}{c.capacity ? <span className="text-zinc-500">/{c.capacity}</span> : ""}</td>
                  <td className="px-3 py-3 tabular-nums text-zinc-300">{c._count.speakers}</td>
                  <td className="px-3 py-3 tabular-nums text-zinc-300">{c._count.sponsors}</td>
                  <td className="px-3 py-3 tabular-nums text-zinc-300">{formatMoney(c.registrations.reduce((s, r) => s + r.amount, 0))}</td>
                  <td className="whitespace-nowrap px-3 py-3 text-xs text-zinc-500">{fmtDate(c.createdAt)}</td>
                  <td className="px-3 py-3">
                    <details className="relative">
                      <summary className="cursor-pointer select-none rounded-lg border border-white/70 bg-white/60 px-2.5 py-1.5 text-xs font-medium text-zinc-300 transition hover:bg-white/90 [&::-webkit-details-marker]:hidden">
                        Actions ▾
                      </summary>
                      <div className="absolute right-0 z-20 mt-1 w-44 space-y-0.5 rounded-xl border border-white/80 bg-white/95 p-1.5 shadow-xl backdrop-blur-xl">
                        <Link href={`/dashboard/c/${c.id}`} className="block rounded-lg px-2.5 py-1.5 text-xs text-zinc-300 hover:bg-indigo-500/10 hover:text-indigo-700">🛠 Manage</Link>
                        <Link href={`/dashboard/c/${c.id}/settings`} className="block rounded-lg px-2.5 py-1.5 text-xs text-zinc-300 hover:bg-indigo-500/10 hover:text-indigo-700">✏️ Edit details</Link>
                        <Link href={`/c/${c.slug}`} target="_blank" className="block rounded-lg px-2.5 py-1.5 text-xs text-zinc-300 hover:bg-indigo-500/10 hover:text-indigo-700">🌐 View public site</Link>
                        {canMutate && (
                          <>
                            <form action={duplicateConference.bind(null, c.id)}>
                              <button className="block w-full rounded-lg px-2.5 py-1.5 text-left text-xs text-zinc-300 hover:bg-indigo-500/10 hover:text-indigo-700">📄 Duplicate</button>
                            </form>
                            {c.status === "DRAFT" && (
                              <form action={orgSetConferenceStatus.bind(null, c.id, "PUBLISHED")}>
                                <button className="block w-full rounded-lg px-2.5 py-1.5 text-left text-xs text-emerald-600 hover:bg-emerald-500/10">🚀 Publish</button>
                              </form>
                            )}
                            {c.status === "PUBLISHED" && (
                              <form action={orgSetConferenceStatus.bind(null, c.id, "DRAFT")}>
                                <button className="block w-full rounded-lg px-2.5 py-1.5 text-left text-xs text-amber-600 hover:bg-amber-500/10">⏸ Unpublish</button>
                              </form>
                            )}
                            {c.status !== "ARCHIVED" && (
                              <form action={orgSetConferenceStatus.bind(null, c.id, "ARCHIVED")}>
                                <button className="block w-full rounded-lg px-2.5 py-1.5 text-left text-xs text-zinc-400 hover:bg-zinc-500/10">🗄 Archive</button>
                              </form>
                            )}
                            {canDelete && ["DRAFT", "ARCHIVED"].includes(c.status) && (
                              <form action={orgDeleteConference.bind(null, c.id)}>
                                <button className="block w-full rounded-lg px-2.5 py-1.5 text-left text-xs text-red-500 hover:bg-red-500/10">🗑 Delete permanently</button>
                              </form>
                            )}
                          </>
                        )}
                      </div>
                    </details>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}
      <p className="mt-3 text-xs text-zinc-600">
        {rows.length} of {all.length} conferences · Delete is available for drafts and archived conferences only.
      </p>
    </main>
  );
}

function matchesWith(c: { status: string; startAt: Date; endAt: Date }, key: string, now: Date) {
  switch (key) {
    case "draft": return c.status === "DRAFT";
    case "upcoming": return c.startAt > now && ["PUBLISHED", "DRAFT"].includes(c.status);
    case "ongoing": return c.status === "LIVE" || (c.startAt <= now && c.endAt >= now && c.status === "PUBLISHED");
    case "completed": return c.status === "COMPLETED" || (c.endAt < now && ["PUBLISHED", "LIVE"].includes(c.status));
    case "archived": return c.status === "ARCHIVED";
    default: return true;
  }
}
