import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getStudentGradeSummary } from "@/modules/grades/data-access"
import { StudentGradeSummary } from "@/modules/grades/components/student-grade-summary"
import { GradeFilters } from "@/modules/grades/components/grade-filters"
import { GradeTrendCard } from "@/modules/grades/components/grade-trend-card"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { UserX } from "lucide-react"
import { getParam, type SearchParams } from "@/shared/lib/search-params"

export const dynamic = "force-dynamic"

export default async function StudentGradesPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}) {
  const ctx = await requirePermission(Permissions.GRADE_RECORD_READ)
  const [sp, summary] = await Promise.all([
    searchParams,
    getStudentGradeSummary(ctx.userId),
  ])

  if (!summary) {
    return (
      <div className="space-y-8">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">My Grades</h2>
          <p className="text-muted-foreground">View your grade records.</p>
        </div>
        <EmptyState
          title="No user found"
          description="Unable to load your student profile."
          icon={UserX}
          className="border-none shadow-none"
        />
      </div>
    )
  }

  // 应用筛选
  const q = (getParam(sp, "q") || "").toLowerCase().trim()
  const subjectFilter = getParam(sp, "subject") || "all"
  const typeFilter = getParam(sp, "type") || "all"
  const semesterFilter = getParam(sp, "semester") || "all"

  const filteredRecords = summary.records.filter((r) => {
    if (q && !r.title.toLowerCase().includes(q)) return false
    if (subjectFilter !== "all" && r.subjectName !== subjectFilter) return false
    if (typeFilter !== "all" && r.type !== typeFilter) return false
    if (semesterFilter !== "all" && r.semester !== semesterFilter) return false
    return true
  })

  const filteredSummary = {
    ...summary,
    records: filteredRecords,
  }

  return (
    <div className="space-y-8">
      <div>
        <h2 className="text-2xl font-bold tracking-tight">My Grades</h2>
        <p className="text-muted-foreground">View your grade records.</p>
      </div>
      <GradeFilters />
      {filteredSummary.records.length > 0 && <GradeTrendCard summary={filteredSummary} />}
      <StudentGradeSummary summary={filteredSummary} />
    </div>
  )
}
