"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"
import { Sparkles, BookOpen, Lightbulb, HelpCircle, FileText } 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 { Textarea } from "@/shared/components/ui/textarea"
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 { LessonContentResult } from "@/modules/ai/types"

type ContentType = "activity" | "assessment" | "question" | "material"

type AiLessonContentGeneratorProps = {
  /** 备课主题 */
  topic: string
  /** 学科 */
  subject?: string
  /** 年级 */
  grade?: string
  /** 教材 ID */
  textbookId?: string
  /** 章节 ID */
  chapterId?: string
  /** 生成内容后的回调 */
  onInsertContent?: (result: LessonContentResult) => void
}

/**
 * AI 备课内容生成器
 *
 * 为教师提供 AI 生成教学活动、评估题、讨论题、教学素材的能力。
 * 通过 AiClientProvider 注入服务，不直接 import actions。
 *
 * 使用场景：在备课编辑器侧边栏中作为辅助工具使用。
 */
export function AiLessonContentGenerator({
  topic,
  subject,
  grade,
  textbookId,
  chapterId,
  onInsertContent,
}: AiLessonContentGeneratorProps): React.ReactNode {
  const t = useTranslations("ai")
  const aiClient = useAiClient()
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<LessonContentResult | null>(null)
  const [activeType, setActiveType] = useState<ContentType>("activity")
  const [additionalContext, setAdditionalContext] = useState("")

  const handleGenerate = async (): Promise<void> => {
    if (!topic.trim()) {
      toast.error(t("lessonPrep.error"))
      return
    }
    setLoading(true)
    try {
      const response = await aiClient.generateLessonContent({
        topic,
        subject,
        grade,
        textbookId,
        chapterId,
        contentType: activeType,
        additionalContext: additionalContext.trim() || undefined,
      })
      if (response.success && response.data) {
        setResult(response.data)
        toast.success(t("lessonPrep.generateContent"))
      } else {
        toast.error(response.message ?? t("lessonPrep.error"))
      }
    } catch {
      toast.error(t("lessonPrep.error"))
    } finally {
      setLoading(false)
    }
  }

  const contentTypes: Array<{ type: ContentType; label: string; icon: typeof Sparkles }> = [
    { type: "activity", label: t("lessonPrep.generateActivity"), icon: Lightbulb },
    { type: "assessment", label: t("lessonPrep.generateAssessment"), icon: FileText },
    { type: "question", label: t("lessonPrep.generateQuestion"), icon: HelpCircle },
    { type: "material", label: t("lessonPrep.generateContent"), icon: BookOpen },
  ]

  return (
    <AiErrorBoundary>
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Sparkles className="h-4 w-4 text-primary" />
            {t("lessonPrep.generateContent")}
          </CardTitle>
          <CardDescription>{t("lessonPrep.description")}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 内容类型选择 */}
          <div className="grid grid-cols-2 gap-2">
            {contentTypes.map(({ type, label, icon: Icon }) => (
              <Button
                key={type}
                type="button"
                variant={activeType === type ? "default" : "outline"}
                size="sm"
                className="justify-start"
                onClick={() => setActiveType(type)}
              >
                <Icon className="mr-1 h-3.5 w-3.5" />
                {label}
              </Button>
            ))}
          </div>

          {/* 附加上下文 */}
          <div className="space-y-1">
            <label className="text-xs text-muted-foreground" htmlFor="ai-additional-context">
              {t("lessonPrep.additionalContext")}
            </label>
            <Textarea
              id="ai-additional-context"
              value={additionalContext}
              onChange={(e) => setAdditionalContext(e.target.value)}
              placeholder={t("lessonPrep.additionalContextPlaceholder")}
              className="min-h-16 text-sm"
              maxLength={500}
            />
          </div>

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

          {/* 生成结果 */}
          {loading ? (
            <AiSuggestionSkeleton />
          ) : result ? (
            <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">{result.title}</h4>
                <Badge variant="secondary" className="text-xs">
                  {activeType}
                </Badge>
              </div>
              <p className="whitespace-pre-wrap text-sm text-muted-foreground">
                {result.content}
              </p>
              {onInsertContent ? (
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    onInsertContent(result)
                    toast.success(t("lessonPrep.insertContent"))
                  }}
                >
                  {t("lessonPrep.insertContent")}
                </Button>
              ) : null}
            </div>
          ) : null}
        </CardContent>
      </Card>
    </AiErrorBoundary>
  )
}
