import Link from "next/link";
import { notFound } from "next/navigation";
import { EntriesTable } from "@/components/features/library/entries-table";
import { MoreMenu } from "@/components/features/library/more-menu";
import { NewEntryForm } from "@/components/features/library/new-entry-form";
import { FilterBar } from "@/components/features";
import { Card, EmptyState, PageHeader, Pagination } from "@/components/ui";
import { canAnywhere, type DashboardKind } from "@/lib/authz/context";
import { requireDashboard } from "@/lib/authz/guard";
import { AuthError } from "@/lib/authz/errors";
import { findContentType } from "@/lib/content/registry";
import { getActiveSiteId, listAccessibleSites } from "@/lib/data/sites";
import { buildHref } from "@/lib/list-params";
import { listEntries } from "@/lib/services/content";

const STATUSES = ["DRAFT", "PUBLISHED", "ARCHIVED"] as const;
const first = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v);

export async function LibraryListScreen({ kind, typeKey, searchParams }: { kind: Extract<DashboardKind, "admin" | "editor">; typeKey: string; searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  const ctx = await requireDashboard(kind);
  if (!canAnywhere(ctx, "content.edit")) notFound();
  const siteId = await getActiveSiteId(await listAccessibleSites(ctx));
  const def = siteId ? await findContentType(typeKey, siteId) : undefined;
  if (siteId && !def) notFound();
  if (!siteId || !def) return (<><PageHeader title="Content library" /><Card><EmptyState title="Choose a website" description="Open a website first (Edit in your website list, or the top-bar dropdown)." /></Card></>);

  const sp = await searchParams;
  const q = first(sp.q)?.slice(0, 100) || undefined;
  const statusRaw = first(sp.status);
  const status = STATUSES.find((s) => s === statusRaw);
  const categoryId = first(sp.category)?.slice(0, 40) || undefined;
  const page = Math.max(1, Math.min(10_000, Number(first(sp.page)) || 1));
  let data;
  try {
    data = await listEntries({ siteId, typeKey, q, status, categoryId, page });
  } catch (e) {
    if (e instanceof AuthError) notFound();
    throw e;
  }
  const base = `/dashboard/${kind}`;
  const path = `${base}/libraries/${typeKey}`;
  return (
    <>
      <PageHeader title={def.plural} description={`${def.description} · ${data.site.name}`} actions={
        <div className="flex flex-wrap items-start gap-2">
          <details className="relative">
            <summary className="inline-flex h-10 cursor-pointer list-none items-center rounded-full border-2 border-foreground/70 px-5 text-sm font-semibold hover:bg-muted">Add New Entry</summary>
            <div className="absolute right-0 z-10 mt-1 w-[22rem] max-w-[calc(100vw-2rem)] rounded-md border border-border bg-card p-3 shadow-md"><NewEntryForm base={base} siteId={siteId} typeKey={typeKey} titleLabel={def.titleLabel} /></div>
          </details>
          <MoreMenu siteId={siteId} typeKey={typeKey} plural={def.plural} canImport={data.perms.manage} fieldKeys={def.fields.filter((f) => ["text", "textarea", "link", "select", "number"].includes(f.kind)).map((f) => f.key)} />
        </div>
      } />
      <div className="grid gap-4 lg:grid-cols-[1fr_16rem]">
        <Card>
          <FilterBar action={path} q={q} status={status} statuses={STATUSES} placeholder={`Search ${def.plural.toLowerCase()}`} />
          {data.rows.length === 0 ? <EmptyState title={q || status ? "Nothing matches" : `No ${def.plural.toLowerCase()} yet`} description={q || status ? "Try different filters." : `Create the first one above.`} /> : (
            <EntriesTable siteId={siteId} typeKey={typeKey} hrefBase={path} canManage={data.perms.manage} rows={data.rows.map((r) => ({ id: r.id, title: r.title, slug: r.slug, status: r.status, createdAt: r.createdAt.toISOString(), category: r.category?.name ?? null, tagged: r._count.tags > 0 || r.category !== null }))} />
          )}
          <Pagination page={page} total={data.total} pageSize={data.pageSize} buildHref={(p) => buildHref(path, { q, status, category: categoryId, page: p })} />
        </Card>
        {def.supportsCategories ? (
          <Card className="space-y-2 p-4 text-sm">
            <h2 className="text-sm font-semibold">Categories</h2>
            {data.categories.length === 0 ? <p className="text-muted-foreground">None assigned to this library yet.</p> : (
              <ul className="space-y-1">
                {data.categories.map((c) => (
                  <li key={c.id}><Link href={buildHref(path, { q, status, category: categoryId === c.id ? undefined : c.id })} aria-current={categoryId === c.id ? "true" : undefined} className={categoryId === c.id ? "font-medium underline" : "hover:underline"}>{c.name}</Link> <span className="text-xs text-muted-foreground">({c._count.entries})</span></li>
                ))}
              </ul>
            )}
            {data.perms.manage ? <Link href={`${base}/categories`} className="inline-block text-primary underline">Manage categories</Link> : null}
          </Card>
        ) : null}
      </div>
      <p className="mt-2 text-xs text-muted-foreground">Showing {data.total === 0 ? 0 : (page - 1) * data.pageSize + 1} to {Math.min(page * data.pageSize, data.total)} of {data.total} entries</p>
    </>
  );
}
