import { notFound, redirect } from "next/navigation";
import { DocumentShell } from "@/components/editor/document-shell";
import type { PageOptionsState, DocumentStats } from "@/types/page-options";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import { api } from "@/lib/convex/api";

interface DocumentPageProps {
  params: Promise<{ id: string }>;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  searchParams?: Promise<Record<string, any>>;
}

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;

  if (isConvexEnabled()) {
    const { client } = await getAuthedConvexClient();
    const doc = await client.query(api.documents.getMeta, { id });
    if (!doc) {
      notFound();
    }

    const initialOptions: PageOptionsState = {
      wideLayout: doc.wide_layout ?? false,
      smallText: doc.use_small_text ?? false,
      showHeadingNumbers: doc.show_heading_numbers ?? true,
      showToc: doc.show_toc ?? false,
      showStructure: doc.show_structure ?? false,
      protectEditing: doc.protect_editing ?? false,
      showWordCount: doc.show_word_count ?? true,
    };

    const initialStats: DocumentStats = {
      wordCount: doc.word_count ?? 0,
      characterCount: doc.character_count ?? 0,
      blockCount: doc.block_count ?? 0,
    };

    return (
      <div className="flex h-screen flex-col">
        <div className="min-h-0 flex-1">
          <DocumentShell
            documentId={doc.id}
            workspaceId={doc.workspace_id}
            title={doc.title ?? "无标题"}
            updatedAt={doc.updated_at}
            initialContent={null}
            initialOptions={initialOptions}
            initialStats={initialStats}
            openTableId={openTableId}
          />
        </div>
      </div>
    );
  }

  redirect("/auth");
}
