import type { JSX } from "react"
import { getTeacherClasses } from "@/modules/classes/data-access"
import { getClassGradeStatsWithMeta, getClassRanking } from "@/modules/grades/data-access"
import { getSubjectOptions } from "@/modules/school/data-access"
import { ClassGradeReport } from "@/modules/grades/components/class-grade-report"
import { ExportButton } from "@/modules/grades/components/export-button"
import { StatsClassSelector } from "@/modules/grades/components/stats-class-selector"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { getParam, type SearchParams } from "@/shared/lib/search-params"
import { BarChart3 } from "lucide-react"

export const dynamic = "force-dynamic"

export default async function StatsPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const sp = await searchParams

  const classId = getParam(sp, "classId")
  const subjectId = getParam(sp, "subjectId")

  const [classes, allSubjects] = await Promise.all([
    getTeacherClasses(),
    getSubjectOptions(),
  ])

  if (classes.length === 0) {
    return (
      <div className="h-full flex-1 flex-col space-y-8 p-8 md:flex">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Grade Statistics</h1>
          <p className="text-muted-foreground">View class grade statistics and rankings.</p>
        </div>
        <EmptyState
          title="No classes"
          description="You don't have any classes yet."
          icon={BarChart3}
          className="border-none shadow-none"
        />
      </div>
    )
  }

  const targetClassId = classId ?? classes[0].id
  const targetSubjectId = subjectId && subjectId !== "all" ? subjectId : undefined

  const [stats, ranking] = await Promise.all([
    getClassGradeStatsWithMeta(targetClassId, targetSubjectId),
    getClassRanking(targetClassId, targetSubjectId),
  ])

  const classOptions = classes.map((c) => ({ id: c.id, name: c.name }))
  const subjectOptions = allSubjects.map((s) => ({ id: s.id, name: s.name }))

  return (
    <div className="h-full flex-1 flex-col space-y-8 p-8 md:flex">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Grade Statistics</h1>
          <p className="text-muted-foreground">View class grade statistics and rankings.</p>
        </div>
        <ExportButton
          classId={targetClassId}
          subjectId={targetSubjectId}
          variant="outline"
          label="导出成绩"
        />
      </div>

      <StatsClassSelector
        classes={classOptions}
        subjects={subjectOptions}
        currentClassId={targetClassId}
        currentSubjectId={subjectId ?? "all"}
      />

      <ClassGradeReport stats={stats} ranking={ranking} />
    </div>
  )
}
