import Link from "next/link";
import { notFound } from "next/navigation";
import { Card, EmptyState, PageHeader, StatusBadge, buttonClass } from "@/components/ui";
import { canAnywhere, type DashboardKind } from "@/lib/authz/context";
import { requireDashboard } from "@/lib/authz/guard";
import { AuthError } from "@/lib/authz/errors";
import { getActiveSiteId, listAccessibleSites } from "@/lib/data/sites";
import { requireSiteModule } from "@/lib/data/modules";
import { formatInZone } from "@/lib/time";
import { listEvents } from "@/lib/services/events";

export async function EventsScreen({ kind }: { kind: Extract<DashboardKind, "admin" | "editor"> }) {
  const ctx = await requireDashboard(kind);
  if (!canAnywhere(ctx, "events.edit") && !canAnywhere(ctx, "events.manage")) notFound();
  const siteId = await getActiveSiteId(await listAccessibleSites(ctx));
  if (siteId) await requireSiteModule(ctx, siteId, "events");
  if (!siteId) return (<><PageHeader title="Events" /><Card><EmptyState title="Choose a website" description="Open a website first (Edit in your website list, or the top-bar dropdown) to manage its events." /></Card></>);
  let data;
  try { data = await listEvents(siteId); } catch (e) { if (e instanceof AuthError) notFound(); throw e; }
  const base = `/dashboard/${kind}/events`;
  return (
    <>
      <PageHeader title="Events" description={data.site.name} actions={data.canManage ? <Link href={`${base}/new`} className={buttonClass("primary")}>New event</Link> : undefined} />
      <Card>
        {data.rows.length === 0 ? <EmptyState title="No events yet" description={data.canManage ? "Create your first event to add tracks, sessions and speakers." : "Nothing to show."} /> : (
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead className="border-b border-border text-xs text-muted-foreground"><tr><th className="px-4 py-2 font-medium">Event</th><th className="px-4 py-2 font-medium">When</th><th className="px-4 py-2 font-medium">Sessions</th><th className="px-4 py-2 font-medium">Status</th></tr></thead>
              <tbody className="divide-y divide-border">
                {data.rows.map((e) => (
                  <tr key={e.id}>
                    <td className="px-4 py-2 font-medium"><Link href={`${base}/${e.id}`} className="hover:underline">{e.name}</Link>{e.venue ? <span className="block text-xs font-normal text-muted-foreground">{e.venue}</span> : null}</td>
                    <td className="px-4 py-2">{formatInZone(e.startsAt, e.timezone)} – {formatInZone(e.endsAt, e.timezone, "date")}</td>
                    <td className="px-4 py-2">{e._count.sessions} · {e._count.tracks} track{e._count.tracks === 1 ? "" : "s"}</td>
                    <td className="px-4 py-2"><StatusBadge value={e.status} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </>
  );
}
