import Link from "next/link";
import { notFound } from "next/navigation";
import { Badge, Card, EmptyState, PageHeader, 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 { describeField } from "@/lib/modules/schema";
import { getSiteModuleOverview } from "@/lib/services/modules";

/** ShowOff-style Modules page: what this website has, the fields of each content module, and a way into each one. */
export async function SiteModulesScreen({ kind }: { kind: Extract<DashboardKind, "admin" | "editor"> }) {
  const ctx = await requireDashboard(kind);
  if (!canAnywhere(ctx, "content.edit")) notFound();
  const siteId = await getActiveSiteId(await listAccessibleSites(ctx));
  if (!siteId) return (<><PageHeader title="Modules" /><Card><EmptyState title="Choose a website" description="Open a website first (Edit in your website list, or the top-bar dropdown) to see its modules." /></Card></>);
  let d;
  try { d = await getSiteModuleOverview(siteId); } catch (e) { if (e instanceof AuthError) notFound(); throw e; }
  const base = `/dashboard/${kind}`;
  const th = "px-4 py-2 font-medium";
  return (
    <>
      <PageHeader title="Modules" description={`${d.siteName} · the modules available on this website and the fields each content module has. Only modules your platform administrator has added to this website are shown. Ask them to add more.`} />
      <Card className="mb-6">
        <h2 className="px-4 pt-4 text-sm font-semibold">Website tools</h2>
        <div className="overflow-x-auto" tabIndex={0} role="region" aria-label="Website tools table">
          <table className="w-full text-left text-sm">
            <caption className="sr-only">Website tools</caption>
            <thead className="border-b border-border text-xs text-muted-foreground"><tr><th scope="col" className={th}>Module</th><th scope="col" className={th}>What it does</th><th scope="col" className={th}>Status</th><th scope="col" className={th}><span className="sr-only">Open</span></th></tr></thead>
            <tbody className="divide-y divide-border">
              {d.core.map((m) => (
                <tr key={m.key}><td className="px-4 py-2 font-medium">{m.label}</td><td className="px-4 py-2 text-muted-foreground">{m.description}</td><td className="px-4 py-2">{m.enabled ? <Badge tone="success">Enabled</Badge> : <Badge tone="warning">Not licensed</Badge>}</td><td className="px-4 py-2 text-right">{m.enabled ? <Link href={`${base}${m.href}`} className={buttonClass("secondary")} aria-label={`Open ${m.label}`}>Open</Link> : null}</td></tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
      <Card>
        <h2 className="px-4 pt-4 text-sm font-semibold">Content modules</h2>
        <div className="overflow-x-auto" tabIndex={0} role="region" aria-label="Content modules table">
          <table className="w-full text-left text-sm">
            <caption className="sr-only">Content modules and their fields</caption>
            <thead className="border-b border-border text-xs text-muted-foreground"><tr><th scope="col" className={th}>Module</th><th scope="col" className={th}>Fields</th><th scope="col" className={th}>Entries</th><th scope="col" className={th}><span className="sr-only">Open</span></th></tr></thead>
            <tbody className="divide-y divide-border">
              {d.libraries.map((m) => (
                <tr key={m.key} className="align-top">
                  <td className="px-4 py-3"><span className="font-medium">{m.plural}</span> {m.custom ? <Badge tone="info">Custom</Badge> : null}<span className="block text-xs text-muted-foreground">{m.description}</span></td>
                  <td className="px-4 py-3">
                    <details>
                      <summary className="cursor-pointer text-sm">{m.fields.length + 1} fields</summary>
                      <ul className="mt-2 space-y-1 text-xs text-muted-foreground">
                        <li><span className="font-medium text-foreground">{m.titleLabel}</span> (title): Short text, required</li>
                        {m.fields.map((f) => <li key={f.key}><span className="font-medium text-foreground">{f.label}</span>: {describeField(f)}</li>)}
                        {m.supportsFeaturedImage ? <li><span className="font-medium text-foreground">Featured image</span>: Image</li> : null}
                        {m.supportsCategories ? <li><span className="font-medium text-foreground">Category</span>: Choice from this website&apos;s categories</li> : null}
                      </ul>
                    </details>
                  </td>
                  <td className="px-4 py-3">{m.total} total · {m.published} published</td>
                  <td className="px-4 py-3">
                    <div className="flex flex-col items-end gap-1">
                      {d.isSuperAdmin ? <Link href={`/dashboard/modules/${m.key}`} className={buttonClass("secondary")} aria-label={`Edit fields of ${m.plural}`}>Edit fields</Link> : null}
                      <Link href={`${base}/libraries/${m.key}`} className={d.isSuperAdmin ? "text-sm underline" : buttonClass("secondary")} aria-label={`${d.isSuperAdmin ? "Manage entries of" : "Edit"} ${m.plural}`}>{d.isSuperAdmin ? "Entries" : "Edit"}</Link>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </>
  );
}
