"use client"

import { useState } from "react"
import { Button } from "@/shared/components/ui/button"
import { Badge } from "@/shared/components/ui/badge"
import { Card } from "@/shared/components/ui/card"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/components/ui/dialog"
import { Plus, Sparkles } from "lucide-react"
import type { Question } from "@/modules/questions/types"
import { AiQuestionVariantGenerator } from "@/modules/ai/components/ai-question-variant-generator"
import { useAiClientOptional } from "@/modules/ai/context/ai-client-provider"

type QuestionBankListProps = {
  questions: Question[]
  onAdd: (question: Question) => void
  isAdded: (id: string) => boolean
  onLoadMore?: () => void
  hasMore?: boolean
  isLoading?: boolean
  /** 学科（用于 AI 题目变体生成） */
  subject?: string
}

/**
 * 从题目内容中提取纯文本（用于 AI 变体生成）
 *
 * 类型收窄：从 unknown 逐步缩小到具体类型，避免使用 as 断言。
 */
function extractQuestionText(content: unknown): string {
  if (!content) return ""
  if (typeof content === "string") return content
  if (typeof content === "object" && content !== null && "text" in content) {
    const textValue = (content as Record<string, unknown>).text
    if (typeof textValue === "string") return textValue
  }
  try {
    return JSON.stringify(content)
  } catch {
    return ""
  }
}

export function QuestionBankList({ questions, onAdd, isAdded, onLoadMore, hasMore, isLoading, subject }: QuestionBankListProps) {
  const aiClient = useAiClientOptional()

  if (questions.length === 0 && !isLoading) {
    return (
      <div className="text-center py-8 text-muted-foreground">
        No questions found matching your filters.
      </div>
    )
  }

  return (
    <div className="space-y-3 pb-4">
      {questions.map((q) => {
        const added = isAdded(q.id)
        const parsedContent = (() => {
          if (q.content && typeof q.content === "object") return q.content as { text?: string }
          if (typeof q.content === "string") {
            try {
              const parsed = JSON.parse(q.content) as unknown
              if (parsed && typeof parsed === "object") return parsed as { text?: string }
              return { text: q.content }
            } catch {
              return { text: q.content }
            }
          }
          return { text: "" }
        })()
        const typeLabel = typeof q.type === "string" ? q.type.replace("_", " ") : "unknown"
        const questionText = extractQuestionText(q.content)
        return (
          <Card key={q.id} className="p-3 flex gap-3 hover:bg-muted/50 transition-colors">
            <div className="flex-1 space-y-2">
              <div className="flex items-center gap-2">
                <Badge variant="outline" className="text-[10px] uppercase">
                  {typeLabel}
                </Badge>
                <Badge variant="secondary" className="text-[10px]">
                  Lvl {q.difficulty}
                </Badge>
                {q.knowledgePoints?.slice(0, 1).map((kp) => (
                  <Badge key={kp.id} variant="outline" className="text-[10px] truncate max-w-[100px]">
                    {kp.name}
                  </Badge>
                ))}
              </div>
              <p className="text-sm line-clamp-2 text-muted-foreground">
                {parsedContent.text || "No content preview"}
              </p>
            </div>
            <div className="flex items-center gap-1">
              {/* AI 题目变体生成（仅在 AiClientProvider 注入时显示） */}
              {aiClient && questionText ? (
                <AiVariantDialog
                  questionText={questionText}
                  questionType={q.type}
                  difficulty={q.difficulty}
                  subject={subject}
                />
              ) : null}
              <Button
                size="sm"
                variant={added ? "secondary" : "default"}
                disabled={added}
                onClick={() => onAdd(q)}
                className="h-8 w-8 p-0"
              >
                <Plus className="h-4 w-4" />
              </Button>
            </div>
          </Card>
        )
      })}

      {hasMore && (
        <div className="pt-2 text-center">
          <Button
            variant="ghost"
            size="sm"
            onClick={onLoadMore}
            disabled={isLoading}
            className="w-full text-muted-foreground"
          >
            {isLoading ? "Loading..." : "Load More"}
          </Button>
        </div>
      )}

      {isLoading && questions.length === 0 && (
         <div className="space-y-3">
            {[1,2,3].map(i => (
                <div key={i} className="h-20 bg-muted/20 rounded-lg animate-pulse" />
            ))}
         </div>
      )}
    </div>
  )
}

/**
 * AI 题目变体生成对话框
 *
 * 独立组件，仅在用户点击时挂载，避免不必要的渲染。
 */
function AiVariantDialog({
  questionText,
  questionType,
  difficulty,
  subject,
}: {
  questionText: string
  questionType: string
  difficulty: number
  subject?: string
}) {
  const [open, setOpen] = useState(false)

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button
          size="sm"
          variant="outline"
          className="h-8 w-8 p-0"
          title="AI variant"
        >
          <Sparkles className="h-4 w-4" />
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Sparkles className="h-4 w-4 text-primary" />
            AI Variant
          </DialogTitle>
        </DialogHeader>
        <AiQuestionVariantGenerator
          originalQuestion={{
            text: questionText,
            type: questionType,
            difficulty,
          }}
          subject={subject}
        />
      </DialogContent>
    </Dialog>
  )
}
