import { BookOpen } from "lucide-react"
import { getTranslations } from "next-intl/server"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import {
  getChildren,
  getChildBasicInfo,
} from "@/modules/parent/data-access"
import { getStudentSelections } from "@/modules/elective/data-access-selections"
import {
  ParentChildrenDataPage,
  ParentNoChildrenPage,
} from "@/modules/parent/components/parent-children-data-page"
import { ParentSelectionView } from "@/modules/elective/components/parent-selection-view"

export const dynamic = "force-dynamic"

interface ChildSelectionData {
  studentId: string
  studentName: string
  selections: Awaited<ReturnType<typeof getStudentSelections>>
}

export default async function ParentElectivePage() {
  const t = await getTranslations("elective")
  const ctx = await requirePermission(Permissions.ELECTIVE_READ)
  const parentId = ctx.userId

  // dataScope 校验：家长必须有关联子女才能查看选课信息
  if (ctx.dataScope.type !== "children" || ctx.dataScope.childrenIds.length === 0) {
    return (
      <ParentNoChildrenPage
        title={t("parent.title")}
        description={t("parent.description")}
        icon={BookOpen}
        emptyTitle={t("parent.noChildrenTitle")}
        emptyDescription={t("parent.noChildrenDescription")}
      />
    )
  }

  // 并行拉取每个子女的选课记录，使用 allSettled 容错
  const relations = await getChildren(parentId)
  const results = await Promise.allSettled(
    relations.map(async (r): Promise<ChildSelectionData> => {
      // 双重校验：parentId + studentId 必须存在关联关系，防止跨家庭信息泄露
      const basicInfo = await getChildBasicInfo(r.studentId, r.relation)
      const selections = await getStudentSelections(r.studentId)
      return {
        studentId: r.studentId,
        studentName: basicInfo?.name ?? r.studentId,
        selections,
      }
    })
  )

  const validItems = results
    .filter(
      (r): r is PromiseFulfilledResult<ChildSelectionData> =>
        r.status === "fulfilled"
    )
    .map((r) => r.value)

  return (
    <ParentChildrenDataPage
      title={t("parent.title")}
      description={t("parent.description")}
      icon={BookOpen}
      noRecordsTitle={t("parent.noRecordsTitle")}
      noRecordsDescription={t("parent.noRecordsDescription")}
      items={validItems}
      renderItem={(item) => (
        <ParentSelectionView
          selections={item.selections}
          studentName={item.studentName}
        />
      )}
    />
  )
}
