"use client"

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

import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { AiErrorBoundary } from "@/modules/ai/components/ai-error-boundary"
import { AiSuggestionSkeleton } from "@/modules/ai/components/ai-skeleton"
import { useAiClient } from "@/modules/ai/context/ai-client-provider"
import type { QuestionVariantResult } from "@/modules/ai/types"

type VariantType = "same_knowledge_point" | "different_difficulty" | "different_format"

const VARIANT_TYPES: readonly VariantType[] = ["same_knowledge_point", "different_difficulty", "different_format"]

const isVariantType = (value: string): value is VariantType => {
  return VARIANT_TYPES.includes(value as VariantType)
}

type AiQuestionVariantGeneratorProps = {
  /** 原始题目 */
  originalQuestion: {
    text: string
    type: string
    difficulty?: number
    options?: Array<{ id: string; text: string; isCorrect?: boolean }>
    answer?: string
  }
  /** 学科 */
  subject?: string
  /** 生成变体后的回调 */
  onAddVariant?: (variant: QuestionVariantResult) => void
}

/**
 * AI 题目变体生成器
 *
 * 为教师提供从现有题目生成变体的能力：
 * - same_knowledge_point: 同知识点不同表述
 * - different_difficulty: 调整难度
 * - different_format: 转换题型
 *
 * 通过 AiClientProvider 注入服务，不直接 import actions。
 */
export function AiQuestionVariantGenerator({
  originalQuestion,
  subject,
  onAddVariant,
}: AiQuestionVariantGeneratorProps): React.ReactNode {
  const t = useTranslations("ai")
  const aiClient = useAiClient()
  const [loading, setLoading] = useState(false)
  const [variant, setVariant] = useState<QuestionVariantResult | null>(null)
  const [variantType, setVariantType] = useState<VariantType>("same_knowledge_point")

  const handleGenerate = async (): Promise<void> => {
    if (!originalQuestion.text.trim()) {
      toast.error(t("error.invalidInput"))
      return
    }
    setLoading(true)
    try {
      const result = await aiClient.generateQuestionVariant({
        originalQuestion,
        subject,
        variantType,
      })
      if (result.success && result.data) {
        setVariant(result.data)
        toast.success(t("exam.generate"))
      } else {
        toast.error(result.message ?? t("error.variantFailed"))
      }
    } catch {
      toast.error(t("error.variantFailed"))
    } finally {
      setLoading(false)
    }
  }

  const variantTypeLabels: Record<VariantType, string> = {
    same_knowledge_point: t("exam.variantType.same_knowledge_point"),
    different_difficulty: t("exam.variantType.different_difficulty"),
    different_format: t("exam.variantType.different_format"),
  }

  return (
    <AiErrorBoundary>
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Sparkles className="h-4 w-4 text-primary" />
            {t("capability.questionVariant")}
          </CardTitle>
          <CardDescription>{t("exam.variantType.label")}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {/* 变体类型选择 */}
          <div className="space-y-1">
            <label className="text-xs text-muted-foreground" htmlFor="variant-type">
              {t("exam.generate")}
            </label>
            <Select
              value={variantType}
              onValueChange={(value) => {
                if (isVariantType(value)) {
                  setVariantType(value)
                }
              }}
            >
              <SelectTrigger id="variant-type" className="w-full">
                <SelectValue placeholder={t("exam.generate")} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="same_knowledge_point">
                  {variantTypeLabels.same_knowledge_point}
                </SelectItem>
                <SelectItem value="different_difficulty">
                  {variantTypeLabels.different_difficulty}
                </SelectItem>
                <SelectItem value="different_format">
                  {variantTypeLabels.different_format}
                </SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 生成按钮 */}
          <Button
            type="button"
            onClick={handleGenerate}
            disabled={loading || !originalQuestion.text.trim()}
            className="w-full"
          >
            <Sparkles className="mr-1 h-3.5 w-3.5" />
            {loading ? t("exam.generating") : t("exam.generate")}
          </Button>

          {/* 生成结果 */}
          {loading ? (
            <AiSuggestionSkeleton />
          ) : variant ? (
            <div className="space-y-3 rounded-md border p-3">
              <div className="flex items-center justify-between gap-2">
                <h4 className="text-sm font-medium">{variant.text}</h4>
                <Badge variant="secondary" className="text-xs">
                  {t("suggestion.difficulty")}: {variant.difficulty}
                </Badge>
              </div>
              {variant.options && variant.options.length > 0 ? (
                <ul className="text-xs text-muted-foreground space-y-1">
                  {variant.options.map((opt, index) => (
                    <li key={index} className="flex items-center gap-1">
                      <span className="font-medium">{opt.id}.</span>
                      <span>{opt.text}</span>
                      {opt.isCorrect ? (
                        <Badge variant="outline" className="text-xs">
                          ✓
                        </Badge>
                      ) : null}
                    </li>
                  ))}
                </ul>
              ) : null}
              {variant.answer ? (
                <div className="text-xs">
                  <span className="font-medium">{t("exam.sourceText")}:</span>{" "}
                  <span className="text-muted-foreground">{variant.answer}</span>
                </div>
              ) : null}
              {variant.explanation ? (
                <p className="text-xs text-muted-foreground italic">
                  {variant.explanation}
                </p>
              ) : null}
              <div className="flex gap-2">
                {onAddVariant ? (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      onAddVariant(variant)
                      toast.success(t("exam.generate"))
                    }}
                  >
                    <Plus className="mr-1 h-3.5 w-3.5" />
                    {t("exam.addVariant")}
                  </Button>
                ) : null}
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={handleGenerate}
                >
                  <RefreshCw className="mr-1 h-3.5 w-3.5" />
                  {t("suggestion.regenerate")}
                </Button>
              </div>
            </div>
          ) : null}
        </CardContent>
      </Card>
    </AiErrorBoundary>
  )
}
