"use client"

import { useEffect, useMemo, useState } from "react"
import { useTranslations } from "next-intl"
import { getQuestionsAction } from "@/modules/questions/actions"
import { Button } from "@/shared/components/ui/button"
import { useDebounce } from "@/shared/hooks/use-debounce"
import { X } from "lucide-react"
import { QuestionBankFilters } from "@/shared/components/question/question-bank-filters"
import type { ExerciseItem } from "../types"
import type { QuestionType } from "@/modules/questions/types"

interface QuestionRow {
  id: string
  type: string
  difficulty: number
  content: unknown
}

interface Props {
  onPick: (items: ExerciseItem[]) => void
  onClose: () => void
  existingIds: string[]
}

export function QuestionBankPicker({ onPick, onClose, existingIds }: Props) {
  const t = useTranslations("lessonPreparation")
  const [questions, setQuestions] = useState<QuestionRow[]>([])
  const [picked, setPicked] = useState<ExerciseItem[]>([])

  // QuestionBankFilters 使用字符串值，这里转换为 filters 对象
  const [searchValue, setSearchValue] = useState("")
  const [typeValue, setTypeValue] = useState<string>("all")
  const [difficultyValue, setDifficultyValue] = useState<string>("all")

  const filters = useMemo<{
    q?: string
    type?: QuestionType
    difficulty?: number
  }>(() => {
    const newFilters: {
      q?: string
      type?: QuestionType
      difficulty?: number
    } = {}
    if (searchValue) newFilters.q = searchValue
    if (typeValue !== "all") newFilters.type = typeValue as QuestionType
    if (difficultyValue !== "all") newFilters.difficulty = Number(difficultyValue)
    return newFilters
  }, [searchValue, typeValue, difficultyValue])

  // 修复 P1-5：搜索 debounce 300ms
  const debouncedFilters = useDebounce(filters, 300)

  useEffect(() => {
    getQuestionsAction(debouncedFilters).then((res) => {
      if (res.success && res.data) {
        const data = res.data.data
        setQuestions(
          data.map((q) => ({
            id: q.id,
            type: q.type,
            difficulty: q.difficulty,
            content: q.content,
          })),
        )
      }
    })
  }, [debouncedFilters])

  function add(q: QuestionRow) {
    if (existingIds.includes(q.id) || picked.some((p) => p.questionId === q.id)) return
    setPicked((prev) => [
      ...prev,
      {
        questionId: q.id,
        source: "bank",
        score: 5,
        order: prev.length,
      },
    ])
  }

  function previewText(content: unknown): string {
    if (typeof content === "string") return content.slice(0, 80)
    try {
      return JSON.stringify(content).slice(0, 80)
    } catch {
      return ""
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
      <div
        role="dialog"
        aria-modal="true"
        aria-label={t("questionBank.title")}
        className="bg-surface rounded-lg shadow-xl w-[700px] max-h-[80vh] flex flex-col"
      >
        <div className="flex justify-between items-center p-4 border-b">
          <h3 className="font-title-md">{t("questionBank.title")}</h3>
          <button onClick={onClose} aria-label={t("action.close")}>
            <X className="w-4 h-4" aria-hidden="true" />
          </button>
        </div>
        <div className="p-4 border-b">
          <QuestionBankFilters
            search={searchValue}
            onSearchChange={setSearchValue}
            type={typeValue}
            onTypeChange={setTypeValue}
            difficulty={difficultyValue}
            onDifficultyChange={setDifficultyValue}
            layout="default"
          />
        </div>
        <div className="flex-1 overflow-y-auto p-4">
          <div className="space-y-2">
            {questions.map((q) => (
              <div
                key={q.id}
                className="border rounded p-2 flex justify-between items-center"
              >
                <span className="text-sm truncate flex-1 mr-2">{previewText(q.content)}</span>
                <span className="text-xs text-on-surface-variant mr-2">
                  {t(`questionBank.type.${q.type}`)} · {t("questionBank.difficulty", { level: q.difficulty })}
                </span>
                <Button size="sm" variant="outline" onClick={() => add(q)}>
                  {t("questionBank.add")}
                </Button>
              </div>
            ))}
          </div>
        </div>
        <div className="p-4 border-t flex justify-between">
          <span className="text-sm">{t("questionBank.selected", { count: picked.length })}</span>
          <Button
            onClick={() => {
              onPick(picked)
              onClose()
            }}
          >
            {t("questionBank.insert")}
          </Button>
        </div>
      </div>
    </div>
  )
}
