import type { JSX } from "react"
import { notFound } from "next/navigation"
import { getTranslations } from "next-intl/server"
import { getExamById } from "@/modules/exams/data-access"
import { getQuestions } from "@/modules/questions/data-access"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { normalizeStructure } from "@/modules/exams/utils/normalize-structure"
// 直接从具体文件导入纯转换函数和类型,绕过 editor/index.ts barrel,
// 避免 Server Component 连带加载 @tiptap/react 客户端扩展(会触发
// "Class extends value undefined is not a constructor or null" 错误)。
import { examNodesToEditorDoc } from "@/modules/exams/editor/exam-nodes-to-editor-doc"
import { structureToEditorDoc } from "@/modules/exams/editor/structure-to-editor"
import type { EditorJSONContent } from "@/modules/exams/editor/exam-rich-editor-types"
import { ExamRichForm } from "@/modules/exams/components/exam-rich-form"
import type { Question } from "@/modules/questions/types"

export const dynamic = "force-dynamic"

export default async function EditRichExamPage({
  params,
}: {
  params: Promise<{ id: string }>
}): Promise<JSX.Element> {
  const { id } = await params
  const t = await getTranslations("examHomework")

  const ctx = await requirePermission(Permissions.EXAM_UPDATE)
  const exam = await getExamById(id, ctx.dataScope)
  if (!exam) return notFound()

  // 加载 exam 关联的题目(含 content)
  const selectedQuestionIds = (exam.questions || []).map((q) => q.id)
  const selectedResult = selectedQuestionIds.length > 0
    ? await getQuestions({
        ids: selectedQuestionIds,
        pageSize: Math.max(10, selectedQuestionIds.length),
      })
    : { data: [] as Awaited<ReturnType<typeof getQuestions>>["data"] }

  type RawQuestion = (typeof selectedResult.data)[number]
  const toQuestion = (q: RawQuestion): Question => ({
    id: q.id,
    content: q.content,
    type: q.type,
    difficulty: q.difficulty ?? 1,
    createdAt: new Date(q.createdAt),
    updatedAt: new Date(q.updatedAt),
    author: q.author
      ? {
          id: q.author.id,
          name: q.author.name || "Unknown",
          image: q.author.image || null,
        }
      : null,
    knowledgePoints: q.knowledgePoints ?? [],
  })

  const questions = selectedResult.data.map(toQuestion)

  // 把 ExamNode[] + questions 转为 EditorDoc,再转为 Tiptap JSON
  const examNodes = normalizeStructure(exam.structure)
  const editorDoc = examNodesToEditorDoc(examNodes, questions, exam.title)
  const initialContent = structureToEditorDoc(editorDoc) as EditorJSONContent

  return (
    <div className="mx-auto w-full max-w-[1400px] space-y-6 p-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">{t("exam.richEditor.title")}</h1>
        <p className="text-muted-foreground">{t("exam.richEditor.description")}</p>
      </div>
      <ExamRichForm
        mode="edit"
        examId={id}
        initialTitle={exam.title}
        initialContent={initialContent}
      />
    </div>
  )
}
