"use client"

import { useQueryState, parseAsString } from "nuqs"

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

export function ErrorBookFilters() {
  const [search, setSearch] = useQueryState("q", parseAsString.withDefault(""))
  const [status, setStatus] = useQueryState("status", parseAsString.withDefault("all"))
  const [sourceType, setSourceType] = useQueryState("source", parseAsString.withDefault("all"))
  const [dueOnly, setDueOnly] = useQueryState("due", parseAsString.withDefault("all"))

  const hasFilters = Boolean(
    search || status !== "all" || sourceType !== "all" || dueOnly !== "all",
  )

  return (
    <FilterBar
      layout="between"
      gapClassName="gap-4"
      hasFilters={hasFilters}
      onReset={() => {
        setSearch(null)
        setStatus(null)
        setSourceType(null)
        setDueOnly(null)
      }}
    >
      <div className="flex flex-1 flex-wrap items-center gap-2">
        <FilterSearchInput
          value={search}
          onChange={(v) => setSearch(v || null)}
          placeholder="搜索笔记内容..."
          className="flex-1 md:max-w-sm"
          inputClassName="border-muted-foreground/20 pl-8"
        />
        <Select value={status} onValueChange={(val) => setStatus(val === "all" ? null : val)}>
          <SelectTrigger className="w-[140px]">
            <SelectValue placeholder="状态" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">全部状态</SelectItem>
            <SelectItem value="new">待学习</SelectItem>
            <SelectItem value="learning">学习中</SelectItem>
            <SelectItem value="mastered">已掌握</SelectItem>
            <SelectItem value="archived">已归档</SelectItem>
          </SelectContent>
        </Select>
        <Select value={sourceType} onValueChange={(val) => setSourceType(val === "all" ? null : val)}>
          <SelectTrigger className="w-[140px]">
            <SelectValue placeholder="来源" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">全部来源</SelectItem>
            <SelectItem value="exam">考试</SelectItem>
            <SelectItem value="homework">作业</SelectItem>
            <SelectItem value="manual">手动添加</SelectItem>
          </SelectContent>
        </Select>
        <Select value={dueOnly} onValueChange={(val) => setDueOnly(val === "all" ? null : val)}>
          <SelectTrigger className="w-[140px]">
            <SelectValue placeholder="复习" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">全部错题</SelectItem>
            <SelectItem value="due">仅看待复习</SelectItem>
          </SelectContent>
        </Select>
      </div>
    </FilterBar>
  )
}
