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 { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
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 ctx = await requirePermission(Permissions.GRADE_RECORD_READ)
  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>
    )
  }

  // P3 修复：对 class_taught scope 过滤可选班级
  const allowedClassIds =
    ctx.dataScope.type === "class_taught" ? ctx.dataScope.classIds : null
  const scopedClasses = allowedClassIds
    ? classes.filter((c) => allowedClassIds.includes(c.id))
    : classes

  if (scopedClasses.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 accessible classes"
          description="You don't have permission to view any classes."
          icon={BarChart3}
          className="border-none shadow-none"
        />
      </div>
    )
  }

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

  // P3 修复：传递 scope 到 data-access 层
  const [stats, ranking] = await Promise.all([
    getClassGradeStatsWithMeta(
      targetClassId,
      targetSubjectId,
      undefined,
      ctx.dataScope,
      ctx.userId
    ),
    getClassRanking(
      targetClassId,
      targetSubjectId,
      undefined,
      ctx.dataScope,
      ctx.userId
    ),
  ])

  const classOptions = scopedClasses.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>
  )
}
