"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"
import { Sparkles, Lightbulb, BookOpen, TrendingDown } 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 { 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 { WeaknessAnalysisResult, SimilarQuestionResult } from "@/modules/ai/types"

type AiErrorBookAnalysisProps = {
  /** 错题列表（用于薄弱点分析） */
  errorItems: Array<{
    questionText: string
    questionType: string
    knowledgePointIds?: string[]
    errorCount: number
    masteryLevel: number
  }>
  /** 学生 ID */
  studentId: string
  /** 学科 ID */
  subjectId?: string
  /** 当前错题的题目文本（用于相似题推荐） */
  currentQuestionText?: string
  /** 当前题目类型 */
  currentQuestionType?: string
  /** 选中相似题后的回调 */
  onSelectSimilarQuestion?: (question: SimilarQuestionResult) => void
}

/**
 * 错题本 AI 分析组件
 *
 * 集成两个 AI 能力：
 * 1. 相似题推荐：根据当前错题生成同类练习
 * 2. 薄弱点分析：分析错题分布，生成学习建议
 *
 * 通过 AiClientProvider 注入服务，不直接 import actions。
 */
export function AiErrorBookAnalysis({
  errorItems,
  studentId,
  subjectId,
  currentQuestionText,
  currentQuestionType,
  onSelectSimilarQuestion,
}: AiErrorBookAnalysisProps): React.ReactNode {
  const t = useTranslations("ai")
  const aiClient = useAiClient()
  const [similarLoading, setSimilarLoading] = useState(false)
  const [weaknessLoading, setWeaknessLoading] = useState(false)
  const [similarQuestions, setSimilarQuestions] = useState<SimilarQuestionResult[]>([])
  const [weaknessResult, setWeaknessResult] = useState<WeaknessAnalysisResult | null>(null)

  const handleGenerateSimilar = async (): Promise<void> => {
    if (!currentQuestionText || !currentQuestionType) return
    setSimilarLoading(true)
    try {
      const result = await aiClient.suggestSimilarQuestions({
        questionText: currentQuestionText,
        questionType: currentQuestionType,
        subject: subjectId,
        count: 3,
      })
      if (result.success && result.data) {
        setSimilarQuestions(result.data)
        toast.success(t("suggestion.loaded"))
      } else {
        toast.error(result.message ?? t("suggestion.error"))
      }
    } catch {
      toast.error(t("suggestion.error"))
    } finally {
      setSimilarLoading(false)
    }
  }

  const handleAnalyzeWeakness = async (): Promise<void> => {
    if (errorItems.length === 0) return
    setWeaknessLoading(true)
    try {
      const result = await aiClient.analyzeWeakness({
        studentId,
        subjectId,
        errorItems,
      })
      if (result.success && result.data) {
        setWeaknessResult(result.data)
        toast.success(t("errorBook.weaknessAnalysis"))
      } else {
        toast.error(result.message ?? t("error.analysisFailed"))
      }
    } catch {
      toast.error(t("error.analysisFailed"))
    } finally {
      setWeaknessLoading(false)
    }
  }

  const severityVariant = (severity: "high" | "medium" | "low"): "destructive" | "secondary" | "outline" => {
    if (severity === "high") return "destructive"
    if (severity === "medium") return "secondary"
    return "outline"
  }

  return (
    <AiErrorBoundary>
      <div className="space-y-4">
        {/* 相似题推荐 */}
        {currentQuestionText ? (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Sparkles className="h-4 w-4 text-primary" />
                {t("errorBook.similarQuestions")}
              </CardTitle>
              <CardDescription>{t("suggestion.title")}</CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              {similarLoading ? (
                <AiSuggestionSkeleton />
              ) : similarQuestions.length > 0 ? (
                <>
                  {similarQuestions.map((question, index) => (
                    <div key={index} className="rounded-md border p-3 space-y-2">
                      <p className="text-sm">{question.text}</p>
                      {question.difficulty ? (
                        <Badge variant="outline" className="text-xs">
                          {t("suggestion.difficulty")}: {question.difficulty}
                        </Badge>
                      ) : null}
                      {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}
                      {onSelectSimilarQuestion ? (
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => onSelectSimilarQuestion(question)}
                        >
                          {t("suggestion.select")}
                        </Button>
                      ) : null}
                    </div>
                  ))}
                  <Button type="button" variant="outline" size="sm" onClick={handleGenerateSimilar} className="w-full">
                    {t("suggestion.regenerate")}
                  </Button>
                </>
              ) : (
                <Button type="button" variant="outline" size="sm" onClick={handleGenerateSimilar} className="w-full">
                  <Sparkles className="mr-1 h-3.5 w-3.5" />
                  {t("suggestion.generate")}
                </Button>
              )}
            </CardContent>
          </Card>
        ) : null}

        {/* 薄弱点分析 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <TrendingDown className="h-4 w-4 text-primary" />
              {t("errorBook.weaknessAnalysis")}
            </CardTitle>
            <CardDescription>{t("errorBook.weakAreas")}</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {weaknessLoading ? (
              <AiSuggestionSkeleton />
            ) : weaknessResult ? (
              <div className="space-y-4">
                <div className="space-y-2">
                  <h4 className="text-sm font-medium">{t("errorBook.weakAreas")}</h4>
                  {weaknessResult.weakAreas.map((area, index) => (
                    <div key={index} className="rounded-md border p-3 space-y-1">
                      <div className="flex items-center justify-between gap-2">
                        <span className="text-sm font-medium">{area.area}</span>
                        <Badge variant={severityVariant(area.severity)}>
                          {t(`errorBook.severity.${area.severity}`)}
                        </Badge>
                      </div>
                      <p className="text-xs text-muted-foreground">{area.suggestion}</p>
                    </div>
                  ))}
                </div>
                <div className="space-y-1">
                  <h4 className="text-sm font-medium flex items-center gap-1">
                    <Lightbulb className="h-3.5 w-3.5" />
                    {t("errorBook.studyPlan")}
                  </h4>
                  <p className="text-sm text-muted-foreground">{weaknessResult.studyPlan}</p>
                </div>
                {weaknessResult.recommendedResources.length > 0 ? (
                  <div className="space-y-1">
                    <h4 className="text-sm font-medium flex items-center gap-1">
                      <BookOpen className="h-3.5 w-3.5" />
                      {t("errorBook.recommendedResources")}
                    </h4>
                    <ul className="text-sm text-muted-foreground list-disc list-inside space-y-1">
                      {weaknessResult.recommendedResources.map((resource, index) => (
                        <li key={index}>{resource}</li>
                      ))}
                    </ul>
                  </div>
                ) : null}
                <Button type="button" variant="outline" size="sm" onClick={handleAnalyzeWeakness} className="w-full">
                  {t("suggestion.regenerate")}
                </Button>
              </div>
            ) : (
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={handleAnalyzeWeakness}
                disabled={errorItems.length === 0}
                className="w-full"
              >
                <TrendingDown className="mr-1 h-3.5 w-3.5" />
                {t("suggestion.generate")}
              </Button>
            )}
          </CardContent>
        </Card>
      </div>
    </AiErrorBoundary>
  )
}
