"use client"

import { useEffect, useState } from "react"
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"
import { getKnowledgePointOptionsAction } from "../actions"
import type { KnowledgePointOption } from "../types"

export function QuestionFilters() {
  const [search, setSearch] = useQueryState("q", parseAsString.withDefault(""))
  const [type, setType] = useQueryState("type", parseAsString.withDefault("all"))
  const [difficulty, setDifficulty] = useQueryState("difficulty", parseAsString.withDefault("all"))
  const [knowledgePointId, setKnowledgePointId] = useQueryState("kp", parseAsString.withDefault("all"))
  const [knowledgePointOptions, setKnowledgePointOptions] = useState<KnowledgePointOption[]>([])

  useEffect(() => {
    getKnowledgePointOptionsAction()
      .then((result) => {
        setKnowledgePointOptions(result.success && result.data ? result.data : [])
      })
      .catch(() => {
        setKnowledgePointOptions([])
      })
  }, [])

  const hasFilters = Boolean(
    search || type !== "all" || difficulty !== "all" || knowledgePointId !== "all",
  )

  return (
    <FilterBar
      layout="between"
      gapClassName="gap-4"
      hasFilters={hasFilters}
      onReset={() => {
        setSearch(null)
        setType(null)
        setDifficulty(null)
        setKnowledgePointId(null)
      }}
    >
      <div className="flex flex-1 items-center gap-2">
        <FilterSearchInput
          value={search}
          onChange={(v) => setSearch(v || null)}
          placeholder="Search questions..."
          className="flex-1 md:max-w-sm"
          inputClassName="border-muted-foreground/20 pl-8"
        />
        <Select value={type} onValueChange={(val) => setType(val === "all" ? null : val)}>
          <SelectTrigger className="w-[150px]">
            <SelectValue placeholder="Type" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Types</SelectItem>
            <SelectItem value="single_choice">Single Choice</SelectItem>
            <SelectItem value="multiple_choice">Multiple Choice</SelectItem>
            <SelectItem value="judgment">True/False</SelectItem>
            <SelectItem value="text">Short Answer</SelectItem>
            <SelectItem value="composite">Composite</SelectItem>
          </SelectContent>
        </Select>
        <Select value={difficulty} onValueChange={(val) => setDifficulty(val === "all" ? null : val)}>
          <SelectTrigger className="w-[150px]">
            <SelectValue placeholder="Difficulty" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Any Difficulty</SelectItem>
            <SelectItem value="1">Easy (1)</SelectItem>
            <SelectItem value="2">Easy-Med (2)</SelectItem>
            <SelectItem value="3">Medium (3)</SelectItem>
            <SelectItem value="4">Med-Hard (4)</SelectItem>
            <SelectItem value="5">Hard (5)</SelectItem>
          </SelectContent>
        </Select>
        <Select value={knowledgePointId} onValueChange={(val) => setKnowledgePointId(val === "all" ? null : val)}>
          <SelectTrigger className="w-[200px]">
            <SelectValue placeholder="Knowledge Point" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Knowledge Points</SelectItem>
            {knowledgePointOptions.map((kp) => {
              const labelParts = [kp.textbookTitle, kp.chapterTitle, kp.name].filter(Boolean)
              const label = labelParts.join(" · ")
              return (
                <SelectItem key={kp.id} value={kp.id}>
                  {label || kp.name}
                </SelectItem>
              )
            })}
          </SelectContent>
        </Select>
      </div>
    </FilterBar>
  )
}
