import { Stethoscope } from "lucide-react"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getStudentMasterySummary } from "@/modules/diagnostic/data-access"
import { getDiagnosticReports } from "@/modules/diagnostic/data-access-reports"
import { StudentDiagnosticView } from "@/modules/diagnostic/components/student-diagnostic-view"
import {
  ParentChildrenDataPage,
  ParentNoChildrenPage,
} from "@/modules/parent/components/parent-children-data-page"

export const dynamic = "force-dynamic"

export default async function ParentDiagnosticPage() {
  const ctx = await requirePermission(Permissions.DIAGNOSTIC_READ)

  if (ctx.dataScope.type !== "children" || ctx.dataScope.childrenIds.length === 0) {
    return (
      <ParentNoChildrenPage
        title="Children Diagnostic"
        description="View your children's knowledge point mastery and diagnostic reports."
        icon={Stethoscope}
        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(async (id) => {
      const [summary, reports] = await Promise.all([
        getStudentMasterySummary(id),
        getDiagnosticReports({ studentId: id }),
      ])
      return { summary, reports, studentId: id }
    }),
  )
  const validItems = results
    .filter(
      (r): r is PromiseFulfilledResult<{
        summary: Awaited<ReturnType<typeof getStudentMasterySummary>>
        reports: Awaited<ReturnType<typeof getDiagnosticReports>>
        studentId: string
      }> => r.status === "fulfilled",
    )
    .map((r) => r.value)

  return (
    <ParentChildrenDataPage
      title="Children Diagnostic"
      description="View knowledge point mastery and diagnostic reports for all your children."
      icon={Stethoscope}
      noRecordsTitle="No diagnostic data"
      noRecordsDescription="Your children don't have any diagnostic data yet."
      items={validItems}
      renderItem={({ summary, reports }) => (
        <>
          <div className="border-b pb-2">
            <h3 className="text-lg font-semibold">
              {summary?.studentName ?? "Unknown student"}
            </h3>
          </div>
          <StudentDiagnosticView summary={summary} reports={reports} />
        </>
      )}
    />
  )
}
