import Link from "next/link";
import { notFound } from "next/navigation";
import { NewForm } from "@/components/features/forms";
import { FromTemplate } from "@/components/features/modules/from-template";
import { Card, EmptyState, PageHeader, StatusBadge } 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 { listForms } from "@/lib/services/forms";
import { listTemplateChoices } from "@/lib/services/form-templates";

export async function FormsScreen({ kind }: { kind: Extract<DashboardKind, "admin"> }) {
  const ctx = await requireDashboard(kind);
  if (!canAnywhere(ctx, "forms.manage") && !canAnywhere(ctx, "forms.submissions.read")) notFound();
  const siteId = await getActiveSiteId(await listAccessibleSites(ctx));
  if (siteId) await requireSiteModule(ctx, siteId, "forms");
  if (!siteId) return (<><PageHeader title="Forms & submissions" /><Card><EmptyState title="Choose a website" description="Open a website first (Edit in your website list, or the top-bar dropdown) to manage its forms." /></Card></>);
  let data;
  let templates: Awaited<ReturnType<typeof listTemplateChoices>> = [];
  try { data = await listForms(siteId); if (data.perms.manage) templates = await listTemplateChoices(siteId); } catch (e) { if (e instanceof AuthError) notFound(); throw e; }
  const base = `/dashboard/${kind}/forms`;
  return (
    <>
      <PageHeader title="Forms & submissions" description={data.site.name} />
      {data.perms.manage ? <div className="mb-4 space-y-3"><NewForm base={`/dashboard/${kind}`} siteId={siteId} /><FromTemplate base={`/dashboard/${kind}`} siteId={siteId} templates={templates} /></div> : null}
      <Card>
        {data.rows.length === 0 ? <EmptyState title="No forms yet" description={data.perms.manage ? "Create a form, then add it to a page with the Form block." : "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">Form</th><th className="px-4 py-2 font-medium">New</th><th className="px-4 py-2 font-medium">Total</th><th className="px-4 py-2 font-medium">Status</th></tr></thead>
              <tbody className="divide-y divide-border">
                {data.rows.map((f) => (
                  <tr key={f.id}>
                    <td className="px-4 py-2 font-medium"><Link href={`${base}/${f.id}`} className="hover:underline">{f.name}</Link><span className="block text-xs font-normal text-muted-foreground">{f.slug}</span></td>
                    <td className="px-4 py-2">{f.newCount}</td>
                    <td className="px-4 py-2">{f.total}</td>
                    <td className="px-4 py-2"><StatusBadge value={f.status} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </>
  );
}
