import type { JSX } from "react"
import { Suspense } from "react"
import { getTranslations } from "next-intl/server"
import { notFound } from "next/navigation"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getLessonPlanById } from "@/modules/lesson-preparation/data-access"
import { assertPlanInScope } from "@/modules/lesson-preparation/lib/scope-check"
import { getTextbookById, getChaptersByTextbookId, findChapterById } from "@/modules/textbooks/data-access"
import { LessonPlanReadonlyView } from "@/modules/lesson-preparation/components/lesson-plan-readonly-view"
import { Skeleton } from "@/shared/components/ui/skeleton"

export const dynamic = "force-dynamic"

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

  const plan = await getLessonPlanById(planId, ctx.userId)
  if (!plan) notFound()

  // V4 P0-1 修复：学生仅可查看本年级已发布课案，防止跨年级信息泄露
  try {
    assertPlanInScope(plan, ctx)
  } catch {
    notFound()
  }

  // 学生只能查看已发布的课案
  if (plan.status !== "published") {
    return (
      <div className="p-6">
        <div className="rounded-md border border-outline-variant bg-surface-container-low p-4 text-on-surface-variant">
          {t("readonly.notPublished")}
        </div>
      </div>
    )
  }

  // 拉取教材/章节标题
  let textbookTitle: string | undefined
  let chapterTitle: string | undefined
  if (plan.textbookId) {
    // V4 P2-1 修复：textbook 和 chapters 查询无依赖关系，改为 Promise.all 并行查询
    const [textbook, chapters] = await Promise.all([
      getTextbookById(plan.textbookId),
      getChaptersByTextbookId(plan.textbookId),
    ])
    textbookTitle = textbook?.title
    if (plan.chapterId) {
      const chapter = findChapterById(chapters, plan.chapterId)
      chapterTitle = chapter?.title
    }
  }

  return (
    <div className="h-[calc(100vh-4rem)]">
      <Suspense
        fallback={
          <div className="flex h-full items-center justify-center">
            <Skeleton className="h-[80%] w-[80%]" />
          </div>
        }
      >
        <LessonPlanReadonlyView
          doc={plan.content}
          textbookTitle={textbookTitle}
          chapterTitle={chapterTitle}
        />
      </Suspense>
    </div>
  )
}
