import type { JSX } from "react"
import { 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 { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Progress } from "@/shared/components/ui/progress"
import { WidgetBoundary } from "@/shared/components/widget-boundary"
import { formatNumber } from "@/shared/lib/utils"

import { getErrorBookStats } from "@/modules/error-book/data-access"
import {
  getStudentNameMap,
  getTopWrongQuestionsByStudentIds,
  getKnowledgePointWeakness,
} from "@/modules/error-book/data-access-analytics"
import { ErrorBookStatsCards } from "@/modules/error-book/components/error-book-stats-cards"
import { TopWrongQuestions } from "@/modules/error-book/components/top-wrong-questions"
import { getTranslations } from "next-intl/server"

export const dynamic = "force-dynamic"

export default async function ParentErrorBookPage(): Promise<JSX.Element> {
  const ctx = await requirePermission(Permissions.ERROR_BOOK_READ)
  const t = await getTranslations("errorBook")

  if (ctx.dataScope.type !== "children" || ctx.dataScope.childrenIds.length === 0) {
    return (
      <div className="flex h-full flex-col space-y-8 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.noChildDesc")}
          className="h-[360px] bg-card"
        />
      </div>
    )
  }

  const childrenIds = ctx.dataScope.childrenIds

  const [nameMap, ...childStatsList] = await Promise.all([
    getStudentNameMap(childrenIds),
    ...childrenIds.map((id) => getErrorBookStats(id)),
  ])

  // 汇总所有子女的错题
  const [topWrongQuestions, weakKps] = await Promise.all([
    getTopWrongQuestionsByStudentIds(childrenIds, 5),
    getKnowledgePointWeakness(childrenIds, 5),
  ])

  return (
    <div className="flex h-full flex-col space-y-8 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>

      {childrenIds.length === 1 ? (
        // 单子女：直接展示统计卡片
        <WidgetBoundary title={t("parent.title")} skeletonHeight={300}>
          <ErrorBookStatsCards stats={childStatsList[0]} />
        </WidgetBoundary>
      ) : (
        // 多子女：每个子女一张卡片
        <WidgetBoundary title={t("parent.title")} skeletonHeight={300}>
          <div className="grid gap-4 md:grid-cols-2">
            {childrenIds.map((childId, idx) => {
              const stats = childStatsList[idx]
              const name = nameMap.get(childId) ?? t("parent.unknown")
              return (
                <Card key={childId}>
                  <CardHeader>
                    <CardTitle className="flex items-center justify-between text-base">
                      <span>{name}</span>
                      <Badge variant="outline">
                        {t("parent.mastery", { rate: formatNumber(stats.masteredRate * 100, 0) })}
                      </Badge>
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="grid grid-cols-2 gap-3 text-sm">
                      <div>
                        <div className="text-muted-foreground">{t("parent.totalErrors")}</div>
                        <div className="text-lg font-bold">{stats.totalCount}</div>
                      </div>
                      <div>
                        <div className="text-muted-foreground">{t("parent.dueReview")}</div>
                        <div className="text-lg font-bold text-rose-600 dark:text-rose-400">
                          {stats.dueReviewCount}
                        </div>
                      </div>
                      <div>
                        <div className="text-muted-foreground">{t("parent.newItems")}</div>
                        <div className="font-medium text-blue-600 dark:text-blue-400">{stats.newCount}</div>
                      </div>
                      <div>
                        <div className="text-muted-foreground">{t("parent.mastered")}</div>
                        <div className="font-medium text-emerald-600 dark:text-emerald-400">{stats.masteredCount}</div>
                      </div>
                    </div>
                    <Progress value={stats.masteredRate * 100} className="h-2" />
                  </CardContent>
                </Card>
              )
            })}
          </div>
        </WidgetBoundary>
      )}

      {/* 薄弱知识点 */}
      {weakKps.length > 0 ? (
        <WidgetBoundary title={t("parent.weakPoints")} skeletonHeight={300}>
          <Card>
            <CardHeader>
              <CardTitle className="text-base">{t("parent.weakPoints")}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {weakKps.map((kp) => (
                  <div key={kp.knowledgePointId} className="space-y-1">
                    <div className="flex items-center justify-between text-sm">
                      <span>{kp.knowledgePointName}</span>
                      <span className="text-muted-foreground">
                        {t("parent.errorsAndMastery", { count: kp.errorCount, rate: formatNumber(kp.masteryRate * 100, 0) })}
                      </span>
                    </div>
                    <Progress value={kp.masteryRate * 100} className="h-1.5" />
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </WidgetBoundary>
      ) : null}

      <WidgetBoundary title={t("parent.weakPoints")} skeletonHeight={300}>
        <TopWrongQuestions questions={topWrongQuestions} />
      </WidgetBoundary>
    </div>
  )
}
