import { Stethoscope, AlertCircle } 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"
import { getUserNamesByIds } from "@/modules/users/data-access"
import { Card, CardContent } from "@/shared/components/ui/card"
import { getTranslations } from "next-intl/server"

export const dynamic = "force-dynamic"

/** v4-P1-9: 单个子女的诊断数据（成功） */
interface ChildDiagnosticSuccessItem {
  studentId: string
  studentName: string
  status: "success"
  summary: Awaited<ReturnType<typeof getStudentMasterySummary>>
  reports: Awaited<ReturnType<typeof getDiagnosticReports>>["reports"]
}

/** v4-P1-9: 单个子女的诊断数据（失败） */
interface ChildDiagnosticErrorItem {
  studentId: string
  studentName: string
  status: "error"
}

type ChildDiagnosticItem = ChildDiagnosticSuccessItem | ChildDiagnosticErrorItem

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

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

  // 预先查询所有子女的姓名，用于错误卡片展示
  const childrenIds = ctx.dataScope.childrenIds
  const nameMap = await getUserNamesByIds(childrenIds)

  // v4-P1-9: 使用 allSettled 容错，但保留 rejected 项渲染错误卡片
  const results = await Promise.allSettled(
    childrenIds.map(async (id) => {
      const [summary, reportsResult] = await Promise.all([
        getStudentMasterySummary(id),
        // v4-P1-3: 家长仅可见已发布报告，避免草稿泄露
        getDiagnosticReports(
          { studentId: id, status: "published" },
          ctx.dataScope,
        ),
      ])
      return { summary, reports: reportsResult.reports, studentId: id }
    }),
  )

  const items: ChildDiagnosticItem[] = results.map((r, idx) => {
    const studentId = childrenIds[idx]
    const studentName = nameMap.get(studentId)?.name ?? t("parent.selectChild")
    if (r.status === "fulfilled") {
      return {
        studentId,
        studentName,
        status: "success" as const,
        summary: r.value.summary,
        reports: r.value.reports,
      }
    }
    // v4-P1-9: rejected 项不再静默丢弃，渲染错误卡片
    return {
      studentId,
      studentName,
      status: "error" as const,
    }
  })

  return (
    <ParentChildrenDataPage
      title={t("parent.title")}
      description={t("parent.description")}
      icon={Stethoscope}
      noRecordsTitle={t("parent.noReportsTitle")}
      noRecordsDescription={t("parent.noRecordsDescription")}
      items={items}
      renderItem={(item) => (
        <>
          <div className="border-b pb-2">
            <h3 className="text-lg font-semibold">{item.studentName}</h3>
          </div>
          {item.status === "success" ? (
            <StudentDiagnosticView
              summary={item.summary}
              reports={item.reports}
              role="parent"
            />
          ) : (
            // v4-P1-9: 错误卡片，提示家长该子女数据加载失败
            <Card className="border-destructive/50">
              <CardContent className="flex flex-col items-center gap-3 py-8 text-center">
                <AlertCircle className="h-8 w-8 text-destructive" aria-hidden="true" />
                <p className="text-sm font-medium text-destructive">
                  {t("error.childLoadFailed", { studentName: item.studentName })}
                </p>
                <p className="text-xs text-muted-foreground">
                  {t("error.childLoadFailedDesc")}
                </p>
              </CardContent>
            </Card>
          )}
        </>
      )}
    />
  )
}
