import { getAuthContext } from "@/shared/lib/auth-guard"
import { getStudentGradeSummary } from "@/modules/grades/data-access"
import { StudentGradeSummary } from "@/modules/grades/components/student-grade-summary"
import {
  ParentChildrenDataPage,
  ParentNoChildrenPage,
} from "@/modules/parent/components/parent-children-data-page"
import { GraduationCap } from "lucide-react"

export const dynamic = "force-dynamic"

export default async function ParentGradesPage() {
  const ctx = await getAuthContext()

  if (ctx.dataScope.type !== "children" || ctx.dataScope.childrenIds.length === 0) {
    return (
      <ParentNoChildrenPage
        title="Children Grades"
        description="View your children's grade records."
        icon={GraduationCap}
        emptyTitle="No children linked"
        emptyDescription="Your account is not linked to any student accounts yet. Please contact the school administrator."
      />
    )
  }

  // 使用 allSettled 容错：单个子女查询失败不影响其他子女展示
  const results = await Promise.allSettled(
    ctx.dataScope.childrenIds.map((id) => getStudentGradeSummary(id)),
  )
  const validSummaries = results
    .filter(
      (r): r is PromiseFulfilledResult<NonNullable<Awaited<ReturnType<typeof getStudentGradeSummary>>>> =>
        r.status === "fulfilled" && r.value !== null,
    )
    .map((r) => r.value)

  return (
    <ParentChildrenDataPage
      title="Children Grades"
      description="View your children's grade records."
      icon={GraduationCap}
      noRecordsTitle="No grade records"
      noRecordsDescription="Your children don't have any grade records yet."
      items={validSummaries}
      renderItem={(summary) => (
        <>
          <h3 className="text-lg font-semibold border-b pb-2">{summary.studentName}</h3>
          <StudentGradeSummary summary={summary} />
        </>
      )}
    />
  )
}
