import { notFound } from "next/navigation";
import { EntryEditor } from "@/components/features/library/entry-editor";
import type { DashboardKind } from "@/lib/authz/context";
import { requireDashboard } from "@/lib/authz/guard";
import { AuthError } from "@/lib/authz/errors";
import { EntryApproval } from "@/components/features/approvals/entry-approval";
import { getEntryApproval } from "@/lib/services/approvals";
import { getEntryEditorData } from "@/lib/services/content";

export async function EntryScreen({ kind, typeKey, entryId }: { kind: Extract<DashboardKind, "admin" | "editor">; typeKey: string; entryId: string }) {
  await requireDashboard(kind);
  let d;
  try {
    d = await getEntryEditorData(entryId);
  } catch (e) {
    if (e instanceof AuthError) notFound();
    throw e;
  }
  if (d.entry.typeKey !== typeKey) notFound(); // the URL's library must match the entry
  const { entry, def } = d;
  const raw = entry.data && typeof entry.data === "object" && !Array.isArray(entry.data) ? (entry.data as Record<string, unknown>) : {};
  let approval: Awaited<ReturnType<typeof getEntryApproval>> | null = null;
  try { approval = await getEntryApproval(entry.siteId, entry.id); } catch (e) { if (!(e instanceof AuthError)) throw e; }
  return (
    <div className="pb-24">
    <EntryEditor
      key={`${entry.id}:${entry.status}`}
      base={`/dashboard/${kind}`}
      typeKey={def.key}
      typeLabel={def.plural}
      titleLabel={def.titleLabel}
      fields={[...def.fields]}
      supportsCategories={def.supportsCategories}
      supportsFeaturedImage={def.supportsFeaturedImage}
      categories={d.categories}
      versions={d.versions.map((v) => ({ version: v.version, createdAt: v.createdAt.toISOString(), author: v.createdBy.name }))}
      perms={d.perms}
      entry={{ id: entry.id, siteId: entry.siteId, status: entry.status, draftVersion: entry.draftVersion, title: entry.title, slug: entry.slug, data: raw, categoryId: entry.categoryId, featuredMediaId: entry.featuredMediaId, seoTitle: entry.seoTitle ?? "", seoDescription: entry.seoDescription ?? "", sortOrder: entry.sortOrder, tags: entry.tags.map((t) => t.tag.name) }}
    />
    {approval ? <EntryApproval siteId={entry.siteId} entryId={entry.id} current={approval.current ? { status: approval.current.status, comment: approval.current.comment } : null} exhibitors={approval.exhibitors} /> : null}
    </div>
  );
}
