import type { JSX } from "react"
import { Suspense } from "react"
import { getTranslations } from "next-intl/server"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getLessonPlans } from "@/modules/lesson-preparation/data-access"
import { getSubjectOptions } from "@/modules/school/data-access"
import { LessonPlanList } from "@/modules/lesson-preparation/components/lesson-plan-list"
import { LessonPlanProviderSetup } from "@/modules/lesson-preparation/providers/lesson-plan-provider-setup"
import { STUDENT_ROLE_CONFIG } from "@/modules/lesson-preparation/providers/lesson-plan-provider"
import { Skeleton } from "@/shared/components/ui/skeleton"

export const dynamic = "force-dynamic"

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

  const [items, subjects] = await Promise.all([
    getLessonPlans({ status: "published" }, ctx.dataScope, ctx.userId),
    getSubjectOptions(),
  ])

  return (
    <div className="p-6 space-y-4">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">{t("student.title")}</h1>
        <p className="text-muted-foreground">{t("student.description")}</p>
      </div>
      {/* P0-13 修复：包裹 LessonPlanProviderSetup，注入 student 角色配置，使筛选功能生效 */}
      <LessonPlanProviderSetup roleConfig={STUDENT_ROLE_CONFIG}>
        <Suspense
          fallback={
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {Array.from({ length: 6 }).map((_, i) => (
                <Skeleton key={i} className="h-[180px] w-full" />
              ))}
            </div>
          }
        >
          <LessonPlanList
            initialItems={items}
            subjects={subjects}
            viewMode="student"
          />
        </Suspense>
      </LessonPlanProviderSetup>
    </div>
  )
}
