import { getAuthContext } from "@/shared/lib/auth-guard"
import { getStudentAttendanceSummary } from "@/modules/attendance/data-access-stats"
import { StudentAttendanceView } from "@/modules/attendance/components/student-attendance-view"
import {
  ParentChildrenDataPage,
  ParentNoChildrenPage,
} from "@/modules/parent/components/parent-children-data-page"
import { CalendarCheck } from "lucide-react"

export const dynamic = "force-dynamic"

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

  if (ctx.dataScope.type !== "children" || ctx.dataScope.childrenIds.length === 0) {
    return (
      <ParentNoChildrenPage
        title="Children Attendance"
        description="View your children's attendance records."
        icon={CalendarCheck}
        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) => getStudentAttendanceSummary(id)),
  )
  const validSummaries = results
    .filter(
      (r): r is PromiseFulfilledResult<NonNullable<Awaited<ReturnType<typeof getStudentAttendanceSummary>>>> =>
        r.status === "fulfilled" && r.value !== null,
    )
    .map((r) => r.value)

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