import type { JSX } from "react"
import { getTranslations } from "next-intl/server"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getCoursePlans } from "@/modules/course-plans/data-access"
import { CoursePlanList } from "@/modules/course-plans/components/course-plan-list"
import { getStudentActiveClassId } from "@/modules/classes/data-access"

export const dynamic = "force-dynamic"

export default async function ParentCoursePlansPage(): Promise<JSX.Element> {
  const ctx = await requirePermission(Permissions.COURSE_PLAN_READ)
  const t = await getTranslations("coursePlans")

  // 家长视角：解析所有孩子的班级 ID，用于过滤课程计划
  let classIds: string[] = []
  if (ctx.dataScope.type === "children" && ctx.dataScope.childrenIds.length > 0) {
    const results = await Promise.all(
      ctx.dataScope.childrenIds.map((sid) => getStudentActiveClassId(sid))
    )
    classIds = results.filter((id): id is string => id !== null)
  }

  const plans =
    classIds.length > 0
      ? await getCoursePlans(
          { status: "active" },
          { userId: ctx.userId, isAdmin: false, classIds }
        )
      : []

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div className="space-y-1">
        <h1 className="text-2xl font-bold tracking-tight">{t("parent.title")}</h1>
        <p className="text-muted-foreground">{t("parent.description")}</p>
      </div>
      <CoursePlanList
        plans={plans}
        detailBaseHref="/parent/course-plans"
      />
    </div>
  )
}
