import Link from "next/link";
import { notFound } from "next/navigation";
import { LibraryRowActions } from "@/components/features/library/library-row-actions";
import { PageSizeSelect } from "@/components/features/library/page-size-select";
import { Card, EmptyState, PageHeader, Pagination, 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 { buildHref } from "@/lib/list-params";
import { getSiteModuleOverview } from "@/lib/services/modules";

const SIZES = [10, 25, 50] as const;
const SORTS = ["name", "entries", "type"] as const;
type Sort = (typeof SORTS)[number];

/** ShowOff-style Libraries page: searchable, sortable, paged list of the content libraries this website has. */
export async function LibrariesScreen({ kind, q, sort, dir, page, size }: { kind: Extract<DashboardKind, "admin" | "editor">; q: string; sort: string; dir: string; page: number; size: number }) {
  const ctx = await requireDashboard(kind);
  if (!canAnywhere(ctx, "content.edit")) notFound();
  const siteId = await getActiveSiteId(await listAccessibleSites(ctx));
  if (!siteId) return (<><PageHeader title="Libraries" /><Card><EmptyState title="Choose a website" description="Open a website first to see its libraries." /></Card></>);
  let d;
  try { d = await getSiteModuleOverview(siteId); } catch (e) { if (e instanceof AuthError) notFound(); throw e; }
  const base = `/dashboard/${kind}`;
  const path = `${base}/libraries`;
  const needle = q.trim().toLowerCase();
  const by: Sort = (SORTS as readonly string[]).includes(sort) ? (sort as Sort) : "name";
  const asc = dir !== "desc";
  const pageSize = (SIZES as readonly number[]).includes(size) ? size : 10;
  const all = d.libraries
    .filter((l) => !needle || l.plural.toLowerCase().includes(needle) || l.label.toLowerCase().includes(needle) || l.key.includes(needle))
    .sort((a, b) => (by === "entries" ? a.total - b.total : by === "type" ? a.key.localeCompare(b.key) : a.plural.localeCompare(b.plural)) * (asc ? 1 : -1));
  const pages = Math.max(1, Math.ceil(all.length / pageSize));
  const current = Math.min(Math.max(1, page), pages);
  const rows = all.slice((current - 1) * pageSize, current * pageSize);
  const th = "px-4 py-3 font-medium";
  const params = { q: q || undefined, sort: by === "name" && asc ? undefined : by, dir: asc ? undefined : "desc", size: pageSize === 10 ? undefined : String(pageSize) };
  const head = (key: Sort, label: string) => (
    <th scope="col" className={th} aria-sort={by === key ? (asc ? "ascending" : "descending") : "none"}>
      <Link href={buildHref(path, { ...params, sort: key, dir: by === key && asc ? "desc" : undefined })} className="inline-flex items-center gap-1 hover:text-foreground">{label}<span aria-hidden className="text-[10px]">{by === key ? (asc ? "▲" : "▼") : "↕"}</span></Link>
    </th>
  );
  return (
    <>
      <PageHeader title="Libraries" description={`${d.siteName} · the content libraries added to this website.`} actions={d.isSuperAdmin ? <Link href="/dashboard/modules/new" className={buttonClass("primary")}>Add New Library</Link> : undefined} />
      <form method="get" role="search" className="mb-4 flex max-w-sm gap-2">
        <label htmlFor="lib-q" className="sr-only">Search libraries</label>
        <input id="lib-q" name="q" defaultValue={q} placeholder="Search…" className="h-9 w-full rounded-md border border-border bg-card px-3 text-sm" />
        {by !== "name" || !asc ? <><input type="hidden" name="sort" value={by} />{asc ? null : <input type="hidden" name="dir" value="desc" />}</> : null}
        {pageSize !== 10 ? <input type="hidden" name="size" value={pageSize} /> : null}
        <button type="submit" className={buttonClass("secondary")}>Search</button>
      </form>
      <Card>
        {all.length === 0 ? <EmptyState title="No libraries" description={needle ? "Nothing matches your search." : "No libraries have been added to this website yet. Ask your platform administrator to add some."} /> : (
          <div className="overflow-x-auto" tabIndex={0} role="region" aria-label="Libraries table">
            <table className="w-full text-left text-sm">
              <caption className="sr-only">Libraries of {d.siteName}</caption>
              <thead className="border-b border-border text-xs text-muted-foreground"><tr>{head("name", "Name")}{head("entries", "Entries")}{head("type", "Type")}<th scope="col" className={th}>Status</th><th scope="col" className={th}><span className="sr-only">Actions</span></th></tr></thead>
              <tbody className="divide-y divide-border">
                {rows.map((l) => (
                  <tr key={l.key}>
                    <td className="px-4 py-3"><Link href={`${path}/${l.key}`} className="font-medium hover:underline">{l.plural}</Link><span className="block text-xs text-muted-foreground">Key: {l.key}</span></td>
                    <td className="px-4 py-3">{l.total}</td>
                    <td className="px-4 py-3">{l.label.toLowerCase()}{l.custom ? <span className="ml-1 text-xs text-muted-foreground">(custom)</span> : null}</td>
                    <td className="px-4 py-3"><span className="inline-flex items-center gap-1.5"><span aria-hidden className="size-2.5 rounded-full bg-success" />Active</span></td>
                    <td className="px-4 py-3"><div className="flex justify-end"><LibraryRowActions base={base} siteId={d.siteId} typeKey={l.key} name={l.plural} superAdmin={d.isSuperAdmin} /></div></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
          <div className="flex items-center gap-3 text-xs text-muted-foreground"><PageSizeSelect href={buildHref(path, { ...params, size: undefined })} value={pageSize} options={SIZES} /><span>Showing {all.length === 0 ? 0 : (current - 1) * pageSize + 1} to {Math.min(current * pageSize, all.length)} of {all.length} entries</span></div>
          <Pagination page={current} total={all.length} pageSize={pageSize} buildHref={(n) => buildHref(path, { ...params, page: String(n) })} />
        </div>
      </Card>
    </>
  );
}
