"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"
import { Sparkles, Check } 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 { Progress } from "@/shared/components/ui/progress"
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 { GradingSuggestion } from "@/modules/ai/types"

type AiGradingAssistProps = {
  /** 题目文本 */
  questionText: string
  /** 题目类型 */
  questionType: string
  /** 学生答案 */
  studentAnswer: string
  /** 正确答案（可选） */
  correctAnswer?: string
  /** 最大分值 */
  maxScore: number
  /** 学科 */
  subject?: string
  /** 应用建议分数 */
  onApplyScore?: (score: number) => void
  /** 应用建议反馈 */
  onApplyFeedback?: (feedback: string) => void
}

/**
 * AI 批改辅助组件
 *
 * 为教师提供 AI 预评分与反馈建议。
 * 仅用于主观题（text/essay），客观题由系统自动判分。
 */
export function AiGradingAssist({
  questionText,
  questionType,
  studentAnswer,
  correctAnswer,
  maxScore,
  subject,
  onApplyScore,
  onApplyFeedback,
}: AiGradingAssistProps): React.ReactNode {
  const t = useTranslations("ai")
  const aiClient = useAiClient()
  const [loading, setLoading] = useState(false)
  const [suggestion, setSuggestion] = useState<GradingSuggestion | null>(null)

  // 仅对主观题提供 AI 批改
  const isAutoGradable = questionType === "single_choice" || questionType === "multiple_choice" || questionType === "judgment"
  if (isAutoGradable) {
    return null
  }

  const handleGenerate = async (): Promise<void> => {
    setLoading(true)
    try {
      const result = await aiClient.suggestGrading({
        questionText,
        questionType,
        studentAnswer,
        correctAnswer,
        maxScore,
        subject,
      })
      if (result.success && result.data) {
        setSuggestion(result.data)
        toast.success(t("grading.title"))
      } else {
        toast.error(result.message ?? t("grading.error"))
      }
    } catch {
      toast.error(t("grading.error"))
    } finally {
      setLoading(false)
    }
  }

  const confidencePercent = suggestion ? Math.round(suggestion.confidence * 100) : 0

  return (
    <AiErrorBoundary>
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Sparkles className="h-4 w-4 text-primary" />
            {t("grading.title")}
          </CardTitle>
          <CardDescription>{t("grading.description")}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {loading ? (
            <AiSuggestionSkeleton />
          ) : suggestion ? (
            <div className="space-y-4">
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">{t("grading.suggestedScore")}</span>
                  <Badge variant="secondary" className="text-base">
                    {suggestion.suggestedScore} / {maxScore}
                  </Badge>
                </div>
                <div className="space-y-1">
                  <div className="flex items-center justify-between text-xs text-muted-foreground">
                    <span>{t("grading.confidence")}</span>
                    <span>{confidencePercent}%</span>
                  </div>
                  <Progress value={confidencePercent} className="h-1.5" />
                </div>
              </div>
              <div className="space-y-1">
                <h4 className="text-sm font-medium">{t("grading.feedback")}</h4>
                <p className="text-sm text-muted-foreground rounded-md bg-muted p-2">
                  {suggestion.feedback}
                </p>
              </div>
              <div className="space-y-1">
                <h4 className="text-sm font-medium">{t("grading.reasoning")}</h4>
                <p className="text-xs text-muted-foreground">{suggestion.reasoning}</p>
              </div>
              <div className="flex gap-2">
                {onApplyScore ? (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      onApplyScore(suggestion.suggestedScore)
                      toast.success(t("grading.suggestedScore"))
                    }}
                  >
                    <Check className="mr-1 h-3.5 w-3.5" />
                    {t("grading.applyScore")}
                  </Button>
                ) : null}
                {onApplyFeedback ? (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      onApplyFeedback(suggestion.feedback)
                      toast.success(t("grading.feedback"))
                    }}
                  >
                    <Check className="mr-1 h-3.5 w-3.5" />
                    {t("grading.applyFeedback")}
                  </Button>
                ) : null}
                <Button type="button" variant="ghost" size="sm" onClick={handleGenerate}>
                  {t("suggestion.regenerate")}
                </Button>
              </div>
            </div>
          ) : (
            <Button type="button" variant="outline" size="sm" onClick={handleGenerate} className="w-full">
              <Sparkles className="mr-1 h-3.5 w-3.5" />
              {t("grading.title")}
            </Button>
          )}
        </CardContent>
      </Card>
    </AiErrorBoundary>
  )
}
