"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"
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 { createId } from "@paralleldrive/cuid2"
import type { Question, QuestionType } from "@/modules/questions/types"
import { QuestionTypeEnum } from "@/modules/questions/schema"
import { AiQuestionVariantGenerator } from "@/modules/ai/components/ai-question-variant-generator"
import { useAiClientOptional } from "@/modules/ai/context/ai-client-provider"
import type { QuestionVariantResult } from "@/modules/ai/types"

/** 合法题型集合，用于运行时校验 AI 返回的 type 字符串 */
const QUESTION_TYPES = new Set<string>(QuestionTypeEnum.options)

/**
 * 类型守卫：校验字符串是否为合法 QuestionType
 *
 * AI 返回的 type 是 string，需收窄为 QuestionType 联合类型，
 * 避免直接使用 as 断言。
 */
function isQuestionType(value: string): value is QuestionType {
  return QUESTION_TYPES.has(value)
}

/**
 * 将 AI 生成的题目变体转换为 Question 对象
 *
 * 变体在客户端生成临时 ID（cuid2），加入试卷结构后随试卷保存时持久化。
 * content 结构与题库一致：{ text, options, answer, explanation }。
 */
function variantToQuestion(variant: QuestionVariantResult): Question {
  const type: QuestionType = isQuestionType(variant.type) ? variant.type : "single_choice"
  return {
    id: createId(),
    content: {
      text: variant.text,
      options: variant.options,
      answer: variant.answer,
      explanation: variant.explanation,
    },
    type,
    difficulty: variant.difficulty,
    createdAt: new Date(),
    updatedAt: new Date(),
    author: null,
    knowledgePoints: [],
  }
}

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): React.ReactNode {
  const t = useTranslations("examHomework.exam.build")
  const aiClient = useAiClientOptional()

  if (questions.length === 0 && !isLoading) {
    return (
      <div className="text-center py-8 text-muted-foreground">
        {t("noQuestionsFound")}
      </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 || t("noContentPreview")}
              </p>
            </div>
            <div className="flex items-center gap-1">
              {/* AI 题目变体生成（仅在 AiClientProvider 注入时显示） */}
              {aiClient && questionText ? (
                <AiVariantDialog
                  questionText={questionText}
                  questionType={q.type}
                  difficulty={q.difficulty}
                  subject={subject}
                  onAdd={onAdd}
                />
              ) : 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 ? t("loading") : t("loadMore")}
          </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,
  onAdd,
}: {
  questionText: string
  questionType: string
  difficulty: number
  subject?: string
  onAdd: (question: Question) => void
}): React.ReactNode {
  const t = useTranslations("examHomework.exam.build")
  const [open, setOpen] = useState(false)

  const handleAddVariant = (variant: QuestionVariantResult): void => {
    onAdd(variantToQuestion(variant))
    setOpen(false)
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button
          size="sm"
          variant="outline"
          className="h-8 w-8 p-0"
          title={t("aiVariant")}
        >
          <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" />
            {t("aiVariant")}
          </DialogTitle>
        </DialogHeader>
        <AiQuestionVariantGenerator
          originalQuestion={{
            text: questionText,
            type: questionType,
            difficulty,
          }}
          subject={subject}
          onAddVariant={handleAddVariant}
        />
      </DialogContent>
    </Dialog>
  )
}
