"use client"

import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
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
}

/**
 * 班级筛选器（教师视图）
 * 显示教师所教的所有班级，点击切换查看单个班级
 *
 * v3: 移除 useSearchParams()，改用 window.location.search 在点击时读取当前 URL 参数。
 * useSearchParams() 在 SSR 期间会导致 Suspense 显示 fallback，CSR 期间显示真实内容，
 * 组件树结构不同导致 useId() 生成的 id 不匹配，触发 hydration mismatch。
 */
export function ClassFilter({
  classes,
  currentClassId,
  paramName = "classId",
}: ClassFilterProps) {
  const router = useRouter()
  const t = useTranslations("errorBook")

  const handleSelect = (classId: string) => {
    // 在 client 端点击时读取当前 URL 参数，避免 useSearchParams() 的 SSR/CSR 不一致
    const params = new URLSearchParams(
      typeof window !== "undefined" ? window.location.search : ""
    )
    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"
        role="tab"
        aria-selected={currentClassId === "all"}
        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">{t("classFilter.all")}</span>
      </button>
      {classes.map((cls) => {
        const isActive = currentClassId === cls.classId
        return (
          <button
            key={cls.classId}
            type="button"
            role="tab"
            aria-selected={isActive}
            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"
            >
              {t("classFilter.errorCount", { count: cls.totalErrorItems })}
            </Badge>
            {cls.dueReviewCount > 0 ? (
              <span
                className={cn(
                  "text-xs",
                  isActive ? "text-primary-foreground/80" : "text-rose-600"
                )}
              >
                {t("classFilter.dueReview", { count: cls.dueReviewCount })}
              </span>
            ) : null}
          </button>
        )
      })}
    </div>
  )
}
