import Link from "next/link";
import { notFound } from "next/navigation";
import type { ReactNode } from "react";
import { Card, EmptyState, PageHeader, buttonClass } from "@/components/ui";
import { canAnywhere, type DashboardKind } from "@/lib/authz/context";
import { requireDashboard } from "@/lib/authz/guard";
import { getActiveSiteId, listAccessibleSites } from "@/lib/data/sites";

export type ReportsKind = Extract<DashboardKind, "admin">;
export const reportsBase = (kind: ReportsKind) => `/dashboard/${kind}/reports`;

/** Common start of every Reports page: sign-in + permission + the active website. Returns the "choose a website" page when none. */
export async function reportsStart(kind: ReportsKind, title: string): Promise<{ siteId: string; empty?: undefined } | { siteId: null; empty: ReactNode }> {
  const ctx = await requireDashboard(kind);
  if (!canAnywhere(ctx, "reports.read")) notFound();
  const siteId = await getActiveSiteId(await listAccessibleSites(ctx));
  if (!siteId) return { siteId: null, empty: (<><PageHeader title={title} /><Card><EmptyState title="Choose a website" description="Open a website first (Edit in your website list, or the top-bar dropdown)." /></Card></>) };
  return { siteId };
}

/** The three shortcuts shown at the top right of the Scheduled Reports pages. */
export function ScheduledReportsNav({ kind, current }: { kind: ReportsKind; current?: "filters" | "schedules" | "history" }) {
  const b = `${reportsBase(kind)}/scheduled`;
  const items = [["filters", "Saved Filters", `${b}/filters`], ["schedules", "Saved Schedules", `${b}/schedules`], ["history", "Schedule History", `${b}/history`]] as const;
  return (
    <nav aria-label="Scheduled reports" className="flex flex-wrap gap-2">
      {items.map(([key, label, href]) => <Link key={key} href={href} aria-current={current === key ? "page" : undefined} className={buttonClass(current === key ? "primary" : "secondary")}>{label}</Link>)}
    </nav>
  );
}
