import type { JSX } from "react"
import type { Metadata } from "next"
import { Suspense } from "react"
import { BarChart3 } from "lucide-react"
import { getTranslations } from "next-intl/server"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { Skeleton } from "@/shared/components/ui/skeleton"
import { WidgetBoundary } from "@/shared/components/widget-boundary"
import { getParam, type SearchParams } from "@/shared/lib/search-params"

import {
  getStudentErrorBookSummaries,
  getTopWrongQuestionsByStudentIds,
  getKnowledgePointWeakness,
  getStudentNameMap,
  getSubjectErrorOverviews,
  getSubjectErrorDistribution,
  getChapterWeakness,
  getAllStudentIds,
} from "@/modules/error-book/data-access-analytics"
import { TopWrongQuestions } from "@/modules/error-book/components/top-wrong-questions"
import { SubjectTabs } from "@/modules/error-book/components/subject-tabs"
import { AnalyticsStatsCards } from "@/modules/error-book/components/analytics-stats-cards"
import { SubjectDistributionChart } from "@/modules/error-book/components/subject-distribution-chart"
import { KnowledgePointWeaknessChart } from "@/modules/error-book/components/knowledge-point-weakness-chart"
import { ChapterWeaknessChart } from "@/modules/error-book/components/chapter-weakness-chart"
import { GroupedStudentErrorTable } from "@/modules/error-book/components/grouped-student-error-table"

export const dynamic = "force-dynamic"

export async function generateMetadata(): Promise<Metadata> {
  const t = await getTranslations("errorBook")
  return {
    title: `${t("admin.title")} - Next_Edu`,
    description: t("admin.description"),
  }
}

async function AdminErrorBookContent({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const t = await getTranslations("errorBook")
  const ctx = await requirePermission(Permissions.ERROR_BOOK_ANALYTICS_READ)

  if (ctx.dataScope.type !== "all") {
    return (
      <div className="flex h-full flex-col space-y-8 p-8">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">{t("admin.title")}</h1>
          <p className="text-muted-foreground">{t("admin.description")}</p>
        </div>
        <EmptyState
          icon={BarChart3}
          title={t("admin.noPermissionTitle")}
          description={t("admin.noPermissionDescription")}
          className="h-[360px] bg-card"
        />
      </div>
    )
  }

  const params = await searchParams

  // 通过 data-access 层查询所有学生 ID（遵循三层架构）
  const allStudentIds = await getAllStudentIds()

  if (allStudentIds.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("admin.title")}</h1>
          <p className="text-muted-foreground">{t("admin.description")}</p>
        </div>
        <EmptyState
          icon={BarChart3}
          title={t("admin.noStudentsTitle")}
          description={t("admin.noStudentsDescription")}
          className="h-[360px] bg-card"
        />
      </div>
    )
  }

  // 限制查询数量，避免性能问题（取最近活跃的 500 名学生）
  const limitedStudentIds = allStudentIds.slice(0, 500)

  // 解析 URL 参数：学科筛选
  const subjectParam = getParam(params, "subject")

  // 学科概览（用于 Tab 显示，不受学科筛选影响）
  const [subjectOverviews, subjectDist] = await Promise.all([
    getSubjectErrorOverviews(limitedStudentIds),
    getSubjectErrorDistribution(limitedStudentIds),
  ])

  // 并行查询所有统计数据（按学科过滤）
  const [summaries, topWrongQuestions, weakKps, chapterWeakness, nameMap] = await Promise.all([
    getStudentErrorBookSummaries(limitedStudentIds, subjectParam),
    getTopWrongQuestionsByStudentIds(limitedStudentIds, 10, subjectParam),
    getKnowledgePointWeakness(limitedStudentIds, 10, subjectParam),
    getChapterWeakness(limitedStudentIds, 10, subjectParam),
    getStudentNameMap(limitedStudentIds),
  ])

  const studentsWithErrorBook = summaries.filter((s) => s.totalCount > 0)
  const totalErrorItems = summaries.reduce((sum, s) => sum + s.totalCount, 0)
  const totalDueReview = summaries.reduce((sum, s) => sum + s.dueReviewCount, 0)
  const averageMasteryRate = studentsWithErrorBook.length > 0
    ? studentsWithErrorBook.reduce((sum, s) => sum + s.masteredRate, 0) / studentsWithErrorBook.length
    : 0
  const knowledgePointCount = weakKps.length

  const sortedSummaries = [...summaries]
    .filter((s) => s.totalCount > 0)
    .sort((a, b) => b.totalCount - a.totalCount)
    .slice(0, 50)

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

      {/* 学科 Tab */}
      {subjectOverviews.length > 0 ? (
        <Suspense fallback={<Skeleton className="h-10 w-full" />}>
          <SubjectTabs
            subjects={subjectOverviews}
            currentSubjectId={subjectParam ?? null}
          />
        </Suspense>
      ) : null}

      {/* 统计卡片 */}
      <WidgetBoundary title={t("admin.title")}>
        <AnalyticsStatsCards
          totalStudents={limitedStudentIds.length}
          studentsWithErrorBook={studentsWithErrorBook.length}
          totalErrorItems={totalErrorItems}
          averageMasteryRate={averageMasteryRate}
          dueReviewCount={totalDueReview}
          knowledgePointCount={knowledgePointCount}
        />
      </WidgetBoundary>

      {/* 学科错题分布图（仅在"全部学科"视图下显示） */}
      {!subjectParam && subjectDist.length > 0 ? (
        <WidgetBoundary title={t("admin.title")}>
          <SubjectDistributionChart data={subjectDist} />
        </WidgetBoundary>
      ) : null}

      {/* 章节错题分布 + 知识点薄弱度（并排） */}
      <div className="grid gap-4 lg:grid-cols-2">
        {chapterWeakness.length > 0 ? (
          <WidgetBoundary title={t("admin.noChapterDataTitle")}>
            <ChapterWeaknessChart data={chapterWeakness} />
          </WidgetBoundary>
        ) : (
          <EmptyState
            icon={BarChart3}
            title={t("admin.noChapterDataTitle")}
            description={t("admin.noChapterDataDescription")}
            className="h-[300px] bg-card"
          />
        )}
        {weakKps.length > 0 ? (
          <WidgetBoundary title={t("admin.noKnowledgePointDataTitle")}>
            <KnowledgePointWeaknessChart data={weakKps} />
          </WidgetBoundary>
        ) : (
          <EmptyState
            icon={BarChart3}
            title={t("admin.noKnowledgePointDataTitle")}
            description={t("admin.noKnowledgePointDataDescription")}
            className="h-[300px] bg-card"
          />
        )}
      </div>

      {/* 错题最多的学生 Top 50 */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold">{t("admin.topStudents")}</h2>
          <span className="text-sm text-muted-foreground">
            {t("admin.studentsWithErrors", { count: studentsWithErrorBook.length })}
          </span>
        </div>
        {sortedSummaries.length > 0 ? (
          <WidgetBoundary title={t("admin.topStudents")}>
            <GroupedStudentErrorTable
              students={sortedSummaries}
              studentNames={nameMap}
              basePath="/admin/error-book"
            />
          </WidgetBoundary>
        ) : (
          <EmptyState
            icon={BarChart3}
            title={t("admin.noStudentErrorsTitle")}
            description={t("admin.noStudentErrorsDescription")}
            className="h-[200px] bg-card"
          />
        )}
      </div>

      {/* 高频错题 Top 10 */}
      {topWrongQuestions.length > 0 ? (
        <WidgetBoundary title={t("admin.title")}>
          <TopWrongQuestions questions={topWrongQuestions} />
        </WidgetBoundary>
      ) : null}
    </div>
  )
}

export default async function AdminErrorBookPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  return (
    <Suspense
      fallback={
        <div className="flex h-full flex-col space-y-8 p-8">
          <Skeleton className="h-10 w-48" />
          <Skeleton className="h-10 w-full" />
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
            {Array.from({ length: 5 }).map((_, i) => (
              <Skeleton key={i} className="h-[100px]" />
            ))}
          </div>
          <Skeleton className="h-[300px] w-full" />
        </div>
      }
    >
      <AdminErrorBookContent searchParams={searchParams} />
    </Suspense>
  )
}
