import { getTranslations } from "next-intl/server"
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 { ParentAttendanceWarning } from "@/modules/parent/components/parent-attendance-warning"
import { ParentAttendanceRateCard } from "@/modules/parent/components/parent-attendance-rate-card"
import { ParentAttendanceCalendar } from "@/modules/parent/components/parent-attendance-calendar"
import { CalendarCheck } from "lucide-react"

export const dynamic = "force-dynamic"

export default async function ParentAttendancePage() {
  const t = await getTranslations("attendance")
  const ctx = await getAuthContext()

  if (ctx.dataScope.type !== "children" || ctx.dataScope.childrenIds.length === 0) {
    return (
      <ParentNoChildrenPage
        title={t("title.parent")}
        description={t("description.parent")}
        icon={CalendarCheck}
        emptyTitle={t("parent.noChildrenTitle")}
        emptyDescription={t("parent.noChildrenDescription")}
      />
    )
  }

  // 使用 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={t("title.parent")}
      description={t("parent.compareDescription")}
      icon={CalendarCheck}
      noRecordsTitle={t("list.empty")}
      noRecordsDescription={t("parent.noRecordsDescription")}
      items={validSummaries}
      renderItem={(summary) => (
        <div className="space-y-6">
          <h3 className="text-lg font-semibold border-b pb-2">{summary.studentName}</h3>
          <ParentAttendanceCalendar summary={summary} />
          <StudentAttendanceView summary={summary} />
        </div>
      )}
      headerExtra={
        validSummaries.length > 0 ? (
          <div className="space-y-4">
            <ParentAttendanceRateCard summaries={validSummaries} />
            <ParentAttendanceWarning summaries={validSummaries} />
          </div>
        ) : null
      }
    />
  )
}
