"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"

import { Checkbox } from "@/shared/components/ui/checkbox"
import { Input } from "@/shared/components/ui/input"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { FormLabel } from "@/shared/components/ui/form"
import { useActionQuery } from "@/shared/hooks/use-action-query"
import { getKnowledgePointOptionsAction } from "../actions"
import type { KnowledgePointOption } from "../types"

interface KnowledgePointSelectorProps {
  selectedIds: string[]
  onChange: (ids: string[]) => void
}

/**
 * 知识点选择器组件。
 *
 * 从 create-question-dialog.tsx 抽取，负责知识点搜索和多选。
 * 使用 useActionQuery 加载知识点选项，支持模糊搜索。
 */
export function KnowledgePointSelector({ selectedIds, onChange }: KnowledgePointSelectorProps): React.ReactNode {
  const t = useTranslations("questions")
  const [query, setQuery] = useState("")

  const { data: knowledgePointOptions, loading: isLoading } = useActionQuery(
    () => getKnowledgePointOptionsAction(),
    { deps: [], errorMessage: false }
  )

  const options = knowledgePointOptions ?? []

  const filteredOptions = options.filter((kp: KnowledgePointOption) => {
    const q = query.trim().toLowerCase()
    if (!q) return true
    const fullLabel = [
      kp.textbookTitle,
      kp.chapterTitle,
      kp.name,
      kp.subject,
      kp.grade,
    ]
      .filter(Boolean)
      .join(" ")
      .toLowerCase()
    return fullLabel.includes(q)
  })

  const toggle = (kpId: string, checked: boolean): void => {
    if (checked) {
      if (selectedIds.includes(kpId)) return
      onChange([...selectedIds, kpId])
    } else {
      onChange(selectedIds.filter((id) => id !== kpId))
    }
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <FormLabel>{t("dialog.knowledgePoints")}</FormLabel>
        <span className="text-xs text-muted-foreground">
          {selectedIds.length > 0
            ? t("dialog.knowledgePointsSelected", { count: selectedIds.length })
            : t("dialog.knowledgePointsOptional")}
        </span>
      </div>
      <Input
        placeholder={t("dialog.searchKnowledgePoints")}
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <div className="rounded-md border">
        <ScrollArea className="h-48">
          {isLoading ? (
            <div className="p-3 text-sm text-muted-foreground">{t("dialog.loading")}</div>
          ) : filteredOptions.length === 0 ? (
            <div className="p-3 text-sm text-muted-foreground">{t("dialog.noKnowledgePoints")}</div>
          ) : (
            <div className="space-y-1 p-2">
              {filteredOptions.map((kp) => {
                const labelParts = [
                  kp.textbookTitle,
                  kp.chapterTitle,
                  kp.name,
                ].filter(Boolean)
                const label = labelParts.join(" · ")
                return (
                  <label key={kp.id} className="flex items-center gap-2 rounded-md px-2 py-1 hover:bg-muted/50">
                    <Checkbox
                      checked={selectedIds.includes(kp.id)}
                      onCheckedChange={(checked) => toggle(kp.id, checked === true)}
                    />
                    <span className="text-sm">{label}</span>
                  </label>
                )
              })}
            </div>
          )}
        </ScrollArea>
      </div>
    </div>
  )
}
