import { notFound, redirect } from "next/navigation";
import { DocumentShell } from "@/components/editor/document-shell";
import { isConvexEnabled } from "@/lib/convex/enabled";
import {
  DEFAULT_EDITOR_HOST_KIND,
  normalizeEditorHostKind,
  resolveEditorHostKind,
  type EditorHostKind,
} from "@/components/editor/editor-host-config";
import { getMnoteRuntimeConfig } from "@/lib/runtime-config";
import { loadPageAggregateFromNextHeaders } from "@/lib/documents/page-aggregate-loader";

interface DocumentPageProps {
  params: Promise<{ id: string }>;
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
}

export default async function DocumentPage({ params, searchParams }: DocumentPageProps) {
  const { id } = await params;
  const resolvedSearch = (await searchParams) ?? {};
  const openTableIdRaw = resolvedSearch?.openTableId;
  const openTableId = typeof openTableIdRaw === "string" ? openTableIdRaw : null;
  const runtimeConfig = getMnoteRuntimeConfig();
  const queryEditorHostRaw = resolvedSearch?.editorHost;
  const queryHostAliasRaw = resolvedSearch?.host;
  const queryHostRaw =
    typeof queryEditorHostRaw === "string"
      ? queryEditorHostRaw
      : typeof queryHostAliasRaw === "string"
        ? queryHostAliasRaw
        : undefined;
  const runtimeHostRaw = runtimeConfig.documentEditorHost;
  const runtimeBlocknoteKillSwitch =
    runtimeConfig.documentEditorBlocknoteKillSwitch === true;

  // 说明：优先级保持稳定且可预期：
  // 1) query（兼容 editorHost，并支持 host 别名）；
  // 2) 运行时配置 documentEditorHost；
  // 3) kill switch（runtime/env）回退到 blocknote；
  // 4) 默认正式主链 leptos_tiptap_island。
  const editorHostKind: EditorHostKind = (() => {
    if (typeof queryHostRaw === "string") {
      return resolveEditorHostKind({
        override: queryHostRaw,
        runtimeDefault: runtimeHostRaw,
      });
    }
    if (runtimeBlocknoteKillSwitch) {
      return "blocknote";
    }
    return normalizeEditorHostKind(runtimeHostRaw, DEFAULT_EDITOR_HOST_KIND);
  })();

  if (isConvexEnabled()) {
    const workspaceIdRaw = resolvedSearch?.workspaceId;
    const workspaceId = typeof workspaceIdRaw === "string" ? workspaceIdRaw : null;
    const loaded = await loadPageAggregateFromNextHeaders({
      documentId: id,
      workspaceId,
    });
    if (!loaded) {
      notFound();
    }

    return (
      <div className="flex h-screen flex-col">
        <div className="min-h-0 flex-1">
          <DocumentShell
            page={loaded.page}
            openTableId={openTableId}
            editorHostKind={editorHostKind}
          />
        </div>
      </div>
    );
  }

  redirect("/auth");
}
