import type { Metadata } from "next"
import type { JSX } 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 { getParam, type SearchParams } from "@/shared/lib/search-params"
import { getTeacherIdForMutations } from "@/modules/classes/data-access"
import { getGradesForStaff } from "@/modules/school/data-access"
import { GradeInsightsFilters } from "@/modules/school/components/grade-insights-filters"

import {
  getGradePracticeOverview,
  getGradeClassPracticeComparison,
  getPracticeTypeBreakdown,
} from "@/modules/adaptive-practice/data-access-analytics"
import { getUserIdsByGradeId } from "@/modules/users/data-access"
import { PracticeOverviewStatsCards } from "@/modules/adaptive-practice/components/practice-overview-stats-cards"
import { ClassPracticeComparisonTable } from "@/modules/adaptive-practice/components/class-practice-comparison-table"
import { PracticeTypeBreakdownChart } from "@/modules/adaptive-practice/components/practice-type-breakdown-chart"

export const dynamic = "force-dynamic"

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

export default async function GradePracticePage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  await requirePermission(Permissions.ADAPTIVE_PRACTICE_READ)
  const t = await getTranslations("practice")
  const params = await searchParams
  const gradeId = getParam(params, "gradeId")

  const teacherId = await getTeacherIdForMutations()
  const grades = await getGradesForStaff(teacherId)
  const allowedIds = new Set(grades.map((g) => g.id))
  const selected = gradeId && gradeId !== "all" && allowedIds.has(gradeId) ? gradeId : ""

  const buildHref = (gId: string): string => {
    const p = new URLSearchParams()
    if (gId && gId !== "all") p.set("gradeId", gId)
    const qs = p.toString()
    return qs ? `/management/grade/practice?${qs}` : "/management/grade/practice"
  }

  if (grades.length === 0) {
    return (
      <div className="flex h-full flex-col space-y-8 p-8">
        <div className="space-y-1">
          <h2 className="text-2xl font-bold tracking-tight">{t("grade.title")}</h2>
          <p className="text-muted-foreground">{t("grade.description")}</p>
        </div>
        <EmptyState
          icon={BarChart3}
          title={t("grade.noGrade")}
          description={t("grade.noGradeDescription")}
          className="h-[360px] bg-card"
        />
      </div>
    )
  }

  // 仅在选中年级时查询数据
  let overview: Awaited<ReturnType<typeof getGradePracticeOverview>> = null
  let classComparison: Awaited<ReturnType<typeof getGradeClassPracticeComparison>> = []
  let typeBreakdown: Awaited<ReturnType<typeof getPracticeTypeBreakdown>> = []

  if (selected) {
    const studentIds = await getUserIdsByGradeId(selected)
    const [ov, cmp, breakdown] = await Promise.all([
      getGradePracticeOverview(selected),
      getGradeClassPracticeComparison(selected),
      getPracticeTypeBreakdown(studentIds),
    ])
    overview = ov
    classComparison = cmp
    typeBreakdown = breakdown
  }

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

      <GradeInsightsFilters
        grades={grades.map((g) => ({ id: g.id, name: g.name, schoolName: g.school.name }))}
        currentGradeId={selected || "all"}
        buildHref={buildHref}
      />

      {!selected ? (
        <EmptyState
          icon={BarChart3}
          title={t("grade.noGrade")}
          description={t("grade.noGradeDescription")}
          className="h-[360px] bg-card"
        />
      ) : !overview ? (
        <EmptyState
          icon={BarChart3}
          title={t("teacher.noData")}
          description={t("teacher.noDataDescription")}
          className="h-[360px] bg-card"
        />
      ) : (
        <div className="space-y-6">
          {/* 年级整体统计卡片 */}
          <PracticeOverviewStatsCards
            totalClasses={overview.totalClasses}
            totalSessions={overview.totalSessions}
            totalAnswered={overview.totalQuestionsAnswered}
            averageAccuracy={overview.averageAccuracy}
            participationRate={overview.participationRate}
          />

          {/* 各班级练习对比表 */}
          {classComparison.length > 0 ? (
            <ClassPracticeComparisonTable data={classComparison} />
          ) : null}

          {/* 练习类型分布图 */}
          {typeBreakdown.length > 0 ? (
            <PracticeTypeBreakdownChart data={typeBreakdown} />
          ) : null}
        </div>
      )}
    </div>
  )
}
