"use client"

import { useRouter, useSearchParams } from "next/navigation"
import { cn } from "@/shared/lib/utils"
import { Badge } from "@/shared/components/ui/badge"

import type { ClassErrorOverview } from "@/modules/error-book/types"

interface ClassFilterProps {
  classes: ClassErrorOverview[]
  /** 当前选中的班级 ID（"all" 表示全部） */
  currentClassId: string
  /** URL 参数名（默认 "classId"） */
  paramName?: string
}

/**
 * 班级筛选器（教师视图）
 * 显示教师所教的所有班级，点击切换查看单个班级
 */
export function ClassFilter({
  classes,
  currentClassId,
  paramName = "classId",
}: ClassFilterProps) {
  const router = useRouter()
  const searchParams = useSearchParams()

  const handleSelect = (classId: string) => {
    const params = new URLSearchParams(searchParams.toString())
    if (classId === "all") {
      params.delete(paramName)
    } else {
      params.set(paramName, classId)
    }
    router.push(`?${params.toString()}`, { scroll: false })
  }

  if (classes.length === 0) return null

  return (
    <div className="flex flex-wrap gap-2">
      <button
        type="button"
        onClick={() => handleSelect("all")}
        className={cn(
          "inline-flex items-center gap-2 rounded-md border px-3 py-1.5 text-sm transition-colors",
          currentClassId === "all"
            ? "border-primary bg-primary text-primary-foreground"
            : "bg-card hover:bg-muted"
        )}
      >
        <span className="font-medium">全部班级</span>
      </button>
      {classes.map((cls) => {
        const isActive = currentClassId === cls.classId
        return (
          <button
            key={cls.classId}
            type="button"
            onClick={() => handleSelect(cls.classId)}
            className={cn(
              "inline-flex items-center gap-2 rounded-md border px-3 py-1.5 text-sm transition-colors",
              isActive
                ? "border-primary bg-primary text-primary-foreground"
                : "bg-card hover:bg-muted"
            )}
          >
            <span className="font-medium">{cls.className}</span>
            <Badge
              variant={isActive ? "secondary" : "outline"}
              className="text-xs"
            >
              {cls.totalErrorItems} 错题
            </Badge>
            {cls.dueReviewCount > 0 ? (
              <span
                className={cn(
                  "text-xs",
                  isActive ? "text-primary-foreground/80" : "text-rose-600"
                )}
              >
                {cls.dueReviewCount} 待复习
              </span>
            ) : null}
          </button>
        )
      })}
    </div>
  )
}
