"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"
import { Sparkles, Check, RefreshCw } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { AiSuggestionSkeleton } from "./ai-skeleton"
import { useAiClient } from "../context/ai-client-provider"
import type { SimilarQuestionResult } from "../types"

type AiSuggestionCardProps = {
  /** 原始题目文本 */
  questionText: string
  /** 题目类型 */
  questionType: string
  /** 学科 */
  subject?: string
  /** 知识点 ID 列表 */
  knowledgePointIds?: string[]
  /** 需要生成的题目数量 */
  count?: number
  /** 选中题目后的回调 */
  onSelectQuestion?: (question: SimilarQuestionResult) => void
}

/**
 * AI 相似题建议卡片
 *
 * 可复用组件，展示 AI 生成的相似练习题。
 * 用于错题本、作业练习等场景。
 */
export function AiSuggestionCard({
  questionText,
  questionType,
  subject,
  knowledgePointIds,
  count = 3,
  onSelectQuestion,
}: AiSuggestionCardProps): React.ReactNode {
  const t = useTranslations("ai")
  const aiClient = useAiClient()
  const [loading, setLoading] = useState(false)
  const [questions, setQuestions] = useState<SimilarQuestionResult[]>([])
  const [hasLoaded, setHasLoaded] = useState(false)

  const handleGenerate = async (): Promise<void> => {
    setLoading(true)
    try {
      const result = await aiClient.suggestSimilarQuestions({
        questionText,
        questionType,
        subject,
        knowledgePointIds,
        count,
      })
      if (result.success && result.data) {
        setQuestions(result.data)
        setHasLoaded(true)
        toast.success(t("suggestion.loaded"))
      } else {
        toast.error(result.message ?? t("suggestion.error"))
      }
    } catch {
      toast.error(t("suggestion.error"))
    } finally {
      setLoading(false)
    }
  }

  const handleSelect = (question: SimilarQuestionResult): void => {
    onSelectQuestion?.(question)
    toast.success(t("suggestion.selected"))
  }

  if (loading) {
    return <AiSuggestionSkeleton />
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Sparkles className="h-4 w-4 text-primary" />
          {t("suggestion.title")}
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-3">
        {hasLoaded && questions.length === 0 ? (
          <p className="text-sm text-muted-foreground">{t("suggestion.empty")}</p>
        ) : questions.length > 0 ? (
          <>
            {questions.map((question, index) => (
              <div
                key={index}
                className="rounded-md border p-3 space-y-2"
              >
                <div className="flex items-start justify-between gap-2">
                  <p className="text-sm flex-1">{question.text}</p>
                  {question.difficulty ? (
                    <Badge variant="outline" className="shrink-0">
                      {t("suggestion.difficulty")}: {question.difficulty}
                    </Badge>
                  ) : null}
                </div>
                {question.options && question.options.length > 0 ? (
                  <ul className="text-xs text-muted-foreground space-y-1">
                    {question.options.map((opt, optIndex) => (
                      <li key={optIndex}>
                        <span className="font-medium">{opt.id}.</span> {opt.text}
                      </li>
                    ))}
                  </ul>
                ) : null}
                {question.explanation ? (
                  <p className="text-xs text-muted-foreground italic">
                    {question.explanation}
                  </p>
                ) : null}
                {onSelectQuestion ? (
                  <div className="flex justify-end gap-2 pt-1">
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => handleSelect(question)}
                    >
                      <Check className="mr-1 h-3.5 w-3.5" />
                      {t("suggestion.select")}
                    </Button>
                  </div>
                ) : null}
              </div>
            ))}
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={handleGenerate}
              className="w-full"
            >
              <RefreshCw className="mr-1 h-3.5 w-3.5" />
              {t("suggestion.regenerate")}
            </Button>
          </>
        ) : (
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={handleGenerate}
            className="w-full"
          >
            <Sparkles className="mr-1 h-3.5 w-3.5" />
            {t("suggestion.generate")}
          </Button>
        )}
      </CardContent>
    </Card>
  )
}
