"use client"

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

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { useActionQuery } from "@/shared/hooks/use-action-query"
import {
  getTextbookOptionsAction,
  getChapterOptionsAction,
  getKnowledgePointOptionsByChapterAction,
} from "../actions"
import type { ChapterOption } from "../types"

/**
 * 题库级联筛选组件：教材 → 章节 → 知识点。
 *
 * 三级级联，选择教材后加载章节，选择章节后加载知识点。
 * 清除上级时自动清除下级。URL 状态通过 nuqs 管理。
 *
 * @example
 * <QuestionCascadeFilter />
 */
export function QuestionCascadeFilter(): React.ReactNode {
  const t = useTranslations("questions")

  const [textbookId, setTextbookId] = useQueryState("tb", parseAsString.withDefault("all"))
  const [chapterId, setChapterId] = useQueryState("ch", parseAsString.withDefault("all"))
  const [knowledgePointId, setKnowledgePointId] = useQueryState("kp", parseAsString.withDefault("all"))

  // 第一级：教材列表
  const { data: textbooks, loading: textbooksLoading } = useActionQuery(
    () => getTextbookOptionsAction(),
    { deps: [], errorMessage: false }
  )

  // 第二级：章节列表（仅当教材已选时加载）
  const { data: chapters, loading: chaptersLoading } = useActionQuery(
    () => getChapterOptionsAction(textbookId),
    { deps: [textbookId], enabled: textbookId !== "all", errorMessage: false }
  )

  // 第三级：知识点列表（仅当章节已选时加载）
  const { data: knowledgePoints, loading: kpsLoading } = useActionQuery(
    () => getKnowledgePointOptionsByChapterAction(chapterId),
    { deps: [chapterId], enabled: chapterId !== "all", errorMessage: false }
  )

  // 清除教材时，自动清除章节和知识点
  const handleTextbookChange = (value: string): void => {
    if (value === "all") {
      setTextbookId(null)
      setChapterId(null)
      setKnowledgePointId(null)
    } else {
      setTextbookId(value)
      setChapterId(null)
      setKnowledgePointId(null)
    }
  }

  // 清除章节时，自动清除知识点
  const handleChapterChange = (value: string): void => {
    if (value === "all") {
      setChapterId(null)
      setKnowledgePointId(null)
    } else {
      setChapterId(value)
      setKnowledgePointId(null)
    }
  }

  const handleKnowledgePointChange = (value: string): void => {
    setKnowledgePointId(value === "all" ? null : value)
  }

  // 章节选项带缩进
  const chapterItems = useMemo(() => {
    if (!chapters) return []
    return chapters.map((ch: ChapterOption) => ({
      id: ch.id,
      title: ch.title,
      indent: ch.depth,
    }))
  }, [chapters])

  return (
    <div className="flex flex-wrap items-center gap-2">
      <Select value={textbookId} onValueChange={handleTextbookChange}>
        <SelectTrigger className="w-[180px]" aria-label={t("filters.textbook")}>
          <SelectValue placeholder={t("filters.textbook")} />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">{t("filters.textbookAll")}</SelectItem>
          {textbooks?.map((tb) => (
            <SelectItem key={tb.id} value={tb.id}>
              {tb.title}
              {tb.grade ? ` (${tb.grade})` : ""}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      <Select
        value={chapterId}
        onValueChange={handleChapterChange}
        disabled={textbookId === "all"}
      >
        <SelectTrigger className="w-[180px]" aria-label={t("filters.chapter")}>
          <SelectValue placeholder={t("filters.chapter")} />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">{t("filters.chapterAll")}</SelectItem>
          {chapterItems.map((ch) => (
            <SelectItem key={ch.id} value={ch.id}>
              {"　".repeat(ch.indent)}{ch.title}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      <Select
        value={knowledgePointId}
        onValueChange={handleKnowledgePointChange}
        disabled={chapterId === "all"}
      >
        <SelectTrigger className="w-[200px]" aria-label={t("filters.knowledgePoint")}>
          <SelectValue placeholder={t("filters.knowledgePoint")} />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">{t("filters.knowledgePointAll")}</SelectItem>
          {knowledgePoints?.map((kp) => (
            <SelectItem key={kp.id} value={kp.id}>
              {kp.name}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {(textbooksLoading || chaptersLoading || kpsLoading) && (
        <span className="text-xs text-muted-foreground animate-pulse" aria-live="polite">
          {t("dialog.loading")}
        </span>
      )}
    </div>
  )
}
