"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 { SubjectErrorOverview } from "@/modules/error-book/types"

interface SubjectTabsProps {
  subjects: SubjectErrorOverview[]
  /** 当前选中的学科 ID（null 表示全部） */
  currentSubjectId: string | null
  /** URL 参数名（默认 "subject"） */
  paramName?: string
}

/**
 * 学科切换 Tab（教师/管理员视图）
 * 显示每个学科的错题数概览，点击切换
 *
 * v3: 移除 useSearchParams()，改用 window.location.search 在点击时读取当前 URL 参数。
 * useSearchParams() 在 SSR 期间会导致 Suspense 显示 fallback，CSR 期间显示真实内容，
 * 组件树结构不同导致 useId() 生成的 id 不匹配，触发 hydration mismatch。
 */
export function SubjectTabs({
  subjects,
  currentSubjectId,
  paramName = "subject",
}: SubjectTabsProps) {
  const router = useRouter()
  const t = useTranslations("errorBook")

  const handleSelect = (subjectId: string | null) => {
    // 在 client 端点击时读取当前 URL 参数，避免 useSearchParams() 的 SSR/CSR 不一致
    const params = new URLSearchParams(
      typeof window !== "undefined" ? window.location.search : ""
    )
    if (subjectId === null) {
      params.delete(paramName)
    } else {
      params.set(paramName, subjectId)
    }
    router.push(`?${params.toString()}`, { scroll: false })
  }

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

  const totalErrors = subjects.reduce((sum, s) => sum + s.totalErrorItems, 0)

  return (
    <div className="flex flex-wrap gap-2">
      <button
        type="button"
        role="tab"
        aria-selected={currentSubjectId === null}
        onClick={() => handleSelect(null)}
        className={cn(
          "inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-colors",
          currentSubjectId === null
            ? "border-primary bg-primary text-primary-foreground"
            : "bg-card hover:bg-muted"
        )}
      >
        <span className="font-medium">{t("subjectTabs.all")}</span>
        <Badge
          variant={currentSubjectId === null ? "secondary" : "outline"}
          className="text-xs"
        >
          {totalErrors}
        </Badge>
      </button>
      {subjects.map((subject) => {
        const isActive = currentSubjectId === subject.subjectId
        return (
          <button
            key={subject.subjectId}
            type="button"
            role="tab"
            aria-selected={isActive}
            onClick={() => handleSelect(subject.subjectId)}
            className={cn(
              "inline-flex items-center gap-2 rounded-full 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">{subject.subjectName}</span>
            <Badge
              variant={isActive ? "secondary" : "outline"}
              className="text-xs"
            >
              {subject.totalErrorItems}
            </Badge>
            {subject.dueReviewCount > 0 ? (
              <span
                className={cn(
                  "text-xs",
                  isActive ? "text-primary-foreground/80" : "text-rose-600"
                )}
              >
                {t("subjectTabs.dueReview", { count: subject.dueReviewCount })}
              </span>
            ) : null}
          </button>
        )
      })}
    </div>
  )
}
