import { notFound } from "next/navigation";
import { MediaBrowser } from "@/components/features/media";
import { Card, EmptyState, PageHeader } from "@/components/ui";
import { can, 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 { db } from "@/lib/db";
import { maxUploadBytes } from "@/lib/media/storage";
import { browseMedia, SORTS, type MediaSort } from "@/lib/services/media-browser";

const first = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v);

export async function MediaScreen({ kind, searchParams }: { kind: Extract<DashboardKind, "admin" | "editor">; searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  const ctx = await requireDashboard(kind);
  if (!canAnywhere(ctx, "media.read")) notFound();
  const path = `/dashboard/${kind}/media`;
  const siteId = await getActiveSiteId(await listAccessibleSites(ctx));
  if (siteId) await requireSiteModule(ctx, siteId, "media");
  if (!siteId) {
    return (
      <>
        <PageHeader title="Media Manager" />
        <Card><EmptyState title="Choose a website" description="Open a website first (Edit in your website list, or the top-bar dropdown) to manage its media." /></Card>
      </>
    );
  }
  const site = await db.site.findUnique({ where: { id: siteId }, select: { id: true, organizationId: true } });
  if (!site) notFound();
  const scope = { siteId: site.id, siteOrganizationId: site.organizationId };
  if (!can(ctx, "media.read", scope)) notFound();

  const sp = await searchParams;
  const sort = (SORTS as readonly string[]).includes(first(sp.sort) ?? "") ? (first(sp.sort) as MediaSort) : "name";
  const q = first(sp.q)?.slice(0, 100) ?? "";
  const desc = first(sp.desc) === "1";
  const view = first(sp.view) === "list" ? "list" : "grid";
  let data;
  try {
    data = await browseMedia({ siteId, path: first(sp.path)?.slice(0, 190), q, sort, desc, perPage: Number(first(sp.perPage)) || 50, page: Math.max(1, Math.min(10_000, Number(first(sp.page)) || 1)) });
  } catch (e) {
    if (e instanceof AuthError) notFound();
    throw e;
  }
  return (
    <MediaBrowser
      siteId={siteId} base={path} params={{ q, sort, desc, view }} canUpload={can(ctx, "media.upload", scope)} canDelete={can(ctx, "media.delete", scope)} maxUploadMb={Math.floor(maxUploadBytes() / 1_000_000)}
      data={{ ...data, files: data.files.map((f) => ({ ...f, usages: f._count.usages, updatedAt: f.updatedAt.toISOString() })) }}
    />
  );
}
