import type { JSX } from "react"
import { getTranslations } from "next-intl/server"
import { Target, Users } from "lucide-react"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { WidgetBoundary } from "@/shared/components/widget-boundary"

import { getPracticeSessions, getPracticeStats } from "@/modules/adaptive-practice/data-access"
import { PracticeHistory } from "@/modules/adaptive-practice/components/practice-history"
import { PracticeStatsCards } from "@/modules/adaptive-practice/components/practice-stats-cards"
import { PracticeServiceProvider } from "@/modules/adaptive-practice/services/practice-service"
import type { PracticeSessionSummary, PracticeStats } from "@/modules/adaptive-practice/types"
import { getUserNamesByIds } from "@/modules/users/data-access"

export const dynamic = "force-dynamic"

interface ChildPracticeItem {
  studentId: string
  studentName: string
  stats: PracticeStats
  sessions: PracticeSessionSummary[]
}

export default async function ParentPracticePage(): Promise<JSX.Element> {
  const ctx = await requirePermission(Permissions.ADAPTIVE_PRACTICE_READ)
  const t = await getTranslations("practice")

  // 家长 dataScope 必须为 children；否则提示无关联子女
  if (ctx.dataScope.type !== "children" || ctx.dataScope.childrenIds.length === 0) {
    return (
      <div className="flex h-full flex-col space-y-8 p-6 md:p-8">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">{t("parent.title")}</h1>
          <p className="text-muted-foreground">{t("parent.description")}</p>
        </div>
        <EmptyState
          icon={Users}
          title={t("parent.noChild")}
          description={t("parent.noChildDescription")}
          className="h-[360px] bg-card"
        />
      </div>
    )
  }

  const childrenIds = ctx.dataScope.childrenIds

  // 并行查询：姓名映射 + 每个子女的统计与历史
  // 使用 allSettled 容错：单个子女查询失败不影响其他子女展示
  // 注意：nameMapPromise 与 childResults 并行启动，但类型上分离以利于类型收窄
  const nameMapPromise = getUserNamesByIds(childrenIds)
  const childResults = await Promise.allSettled(
    childrenIds.map(async (id) => {
      const [stats, sessionsResult] = await Promise.all([
        getPracticeStats(id),
        getPracticeSessions(id, { pageSize: 20 }),
      ])
      return { studentId: id, stats, sessions: sessionsResult.data }
    }),
  )
  const nameMap = await nameMapPromise

  // 过滤掉 rejected 的查询结果
  const validItems: ChildPracticeItem[] = []
  for (const r of childResults) {
    if (r.status !== "fulfilled") continue
    const { studentId, stats, sessions } = r.value
    const studentName = nameMap.get(studentId)?.name ?? t("parent.noChildSelected")
    validItems.push({ studentId, studentName, stats, sessions })
  }

  // 单子女：直接展示；多子女：按卡片分组
  const isSingleChild = validItems.length === 1

  return (
    <PracticeServiceProvider>
      <div className="flex h-full flex-col space-y-8 p-6 md:p-8">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">{t("parent.title")}</h1>
          <p className="text-muted-foreground">{t("parent.description")}</p>
        </div>

        {isSingleChild ? (
          <>
            <WidgetBoundary title={t("parent.stats")} skeletonHeight={160}>
              <PracticeStatsCards stats={validItems[0]!.stats} />
            </WidgetBoundary>
            <div className="space-y-4">
              <h2 className="text-lg font-semibold">{t("parent.history")}</h2>
              <WidgetBoundary title={t("parent.history")} skeletonHeight={300}>
                {/* 家长无会话详情页，仅展示只读卡片 */}
                <PracticeHistory sessions={validItems[0]!.sessions} />
              </WidgetBoundary>
            </div>
          </>
        ) : (
          <div className="space-y-8">
            {validItems.map((item) => (
              <WidgetBoundary
                key={item.studentId}
                title={`${t("parent.stats")} · ${item.studentName}`}
                skeletonHeight={300}
              >
                <div className="space-y-4">
                  <div className="flex items-center gap-2 border-b pb-2">
                    <Target className="h-5 w-5 text-primary" aria-hidden="true" />
                    <h3 className="text-lg font-semibold">{item.studentName}</h3>
                  </div>
                  <PracticeStatsCards stats={item.stats} />
                  <div className="space-y-3">
                    <h4 className="text-sm font-medium text-muted-foreground">
                      {t("parent.history")}
                    </h4>
                    {/* 家长无会话详情页，仅展示只读卡片 */}
                    <PracticeHistory sessions={item.sessions} />
                  </div>
                </div>
              </WidgetBoundary>
            ))}
          </div>
        )}
      </div>
    </PracticeServiceProvider>
  )
}
