import { notFound, redirect } from "next/navigation";
import { createSupabaseServerClient } from "@/lib/supabase/server";
import { DocumentShell } from "@/components/editor/document-shell";
import type { PageOptionsState, DocumentStats } from "@/types/page-options";

interface DocumentPageProps {
  params: Promise<{ id: string }>;
}

export default async function DocumentPage({ params }: DocumentPageProps) {
  const { id } = await params;
  const supabase = await createSupabaseServerClient();
  const {
    data: { session },
  } = await supabase.auth.getSession();

  if (!session) {
    redirect("/login");
  }

  const { data: document } = await supabase
    .from("documents")
    .select(
      "id,title,content,updated_at,workspace_id,wide_layout,use_small_text,show_heading_numbers,show_toc,show_structure,protect_editing,show_word_count,word_count,character_count,block_count",
    )
    .eq("user_id", session.user.id)
    .eq("id", id)
    .single();

  if (!document) {
    notFound();
  }

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

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

  return (
    <DocumentShell
      documentId={document.id}
      workspaceId={document.workspace_id}
      title={document.title}
      updatedAt={document.updated_at}
      initialContent={document.content}
      initialOptions={initialOptions}
      initialStats={initialStats}
    />
  );
}
