"use client"

import { useQueryState, parseAsString } from "nuqs"
import { useTranslations } from "next-intl"

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { FilterBar, FilterSearchInput } from "@/shared/components/ui/filter-bar"
import { SUBJECTS, GRADES } from "../constants"

export function TextbookFilters() {
  const t = useTranslations("textbooks")
  const [search, setSearch] = useQueryState("q", parseAsString.withDefault(""))
  const [subject, setSubject] = useQueryState("subject", parseAsString.withDefault("all"))
  const [grade, setGrade] = useQueryState("grade", parseAsString.withDefault("all"))

  const hasFilters = Boolean(search || subject !== "all" || grade !== "all")

  return (
    <FilterBar
      layout="between"
      hasFilters={hasFilters}
      onReset={() => {
        setSearch(null)
        setSubject(null)
        setGrade(null)
      }}
    >
      <FilterSearchInput
        value={search}
        onChange={(v) => setSearch(v || null)}
        placeholder={t("filters.searchPlaceholder")}
      />

      <div className="flex flex-wrap gap-2 w-full md:w-auto">
        <Select value={subject} onValueChange={(val) => setSubject(val === "all" ? null : val)}>
          {/* 任意值 w-[140px]：学科选择器固定宽度，保证触发器不随内容变化 */}
          <SelectTrigger className="w-[140px] bg-background border-muted-foreground/20">
            <SelectValue placeholder={t("field.subject")} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{t("filters.allSubjects")}</SelectItem>
            {SUBJECTS.map((s) => (
              <SelectItem key={s.value} value={s.value}>
                {t(`subject.${s.labelKey}`)}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Select value={grade} onValueChange={(val) => setGrade(val === "all" ? null : val)}>
          {/* 任意值 w-[130px]：年级选择器固定宽度，保证触发器不随内容变化 */}
          <SelectTrigger className="w-[130px] bg-background border-muted-foreground/20">
            <SelectValue placeholder={t("field.grade")} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{t("filters.allGrades")}</SelectItem>
            {GRADES.map((g) => (
              <SelectItem key={g.value} value={g.value}>
                {t(`grade.${g.labelKey}`)}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    </FilterBar>
  )
}
