import type { JSX } from "react"
import { Suspense } from "react"
import { notFound } from "next/navigation"
import { getLessonPlanById } from "@/modules/lesson-preparation/data-access"
import { LessonPlanEditor } from "@/modules/lesson-preparation/components/lesson-plan-editor"
import { LessonPlanProviderSetup } from "@/modules/lesson-preparation/providers/lesson-plan-provider-setup"
import { getTeacherClasses } from "@/modules/classes/data-access"
import { getTextbookById, getChaptersByTextbookId, findChapterById } from "@/modules/textbooks/data-access"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { Skeleton } from "@/shared/components/ui/skeleton"
import { AiClientProvider } from "@/modules/ai/context/ai-client-provider"
import { createCoreAiClientService } from "@/modules/ai/context/create-ai-client-service"
// P0-11 修复：通过 slot 组件注入 AI 功能，避免备课模块直接 import @/modules/ai
import { AiContentGeneratorSlot } from "./ai-content-generator-slot"

export const dynamic = "force-dynamic"

export default async function EditLessonPlanPage({
  params,
}: {
  params: Promise<{ planId: string }>
}): Promise<JSX.Element> {
  const { planId } = await params
  // V4 P0-2 修复：页面层补齐 requirePermission 权限校验
  const ctx = await requirePermission(Permissions.LESSON_PLAN_READ)

  const [plan, teacherClasses] = await Promise.all([
    getLessonPlanById(planId, ctx.userId),
    getTeacherClasses({ teacherId: ctx.userId }),
  ])
  if (!plan) notFound()

  const classes = teacherClasses.map((c) => ({ id: c.id, name: c.name }))

  // 拉取教材/章节标题用于工具栏显示
  let textbookTitle: string | undefined
  let chapterTitle: string | undefined
  if (plan.textbookId) {
    const textbook = await getTextbookById(plan.textbookId)
    textbookTitle = textbook?.title
    if (plan.chapterId) {
      const chapters = await getChaptersByTextbookId(plan.textbookId)
      // P1-6 修复：使用共享工具 findChapterById 替代页面内重复的递归函数
      const chapter = findChapterById(chapters, plan.chapterId)
      chapterTitle = chapter?.title
    }
  }

  const aiClientService = createCoreAiClientService()

  return (
    <AiClientProvider service={aiClientService}>
      <LessonPlanProviderSetup>
        <div className="h-[calc(100vh-4rem)]">
          <Suspense
            fallback={
              <div className="flex h-full items-center justify-center">
                <Skeleton className="h-[80%] w-[80%]" />
              </div>
            }
          >
            <LessonPlanEditor
              planId={plan.id}
              initialTitle={plan.title}
              initialDoc={plan.content}
              initialStatus={plan.status}
              textbookId={plan.textbookId ?? undefined}
              chapterId={plan.chapterId ?? undefined}
              textbookTitle={textbookTitle}
              chapterTitle={chapterTitle}
              classes={classes}
              aiContentGenerator={AiContentGeneratorSlot}
            />
          </Suspense>
        </div>
      </LessonPlanProviderSetup>
    </AiClientProvider>
  )
}
