"use client"

import { useState, useRef } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Textarea } from "@/components/ui/textarea"
import { Slider } from "@/components/ui/slider"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  Sparkles,
  Wand2,
  Download,
  RefreshCw,
  Copy,
  Heart,
  Share,
  Info,
  Lightbulb,
  AlertCircle,
  CheckCircle,
} from "lucide-react"

interface GenerationConfig {
  prompt: string
  style: string
  creativity: number
  quality: string
  aspectRatio: string
  steps: number
}

interface GeneratedImage {
  id: string
  prompt: string
  url: string
  style: string
  timestamp: Date
  liked: boolean
}

interface GenerationState {
  isGenerating: boolean
  progress: number
  currentStep: string
  phase: "idle" | "processing" | "generating" | "completed"
}

interface ImageGenerationStepProps {
  onNext?: () => void
  selectedImages: string[]
}

const presetPrompts = [
  {
    category: "风景画",
    prompts: [
      "宁静的山湖倒影，晨雾缭绕，水彩画风格",
      "夕阳下的麦田，金黄色调，印象派风格",
      "樱花飞舞的小径，粉色花瓣，日式绘画风格",
      "雪山峰顶，蓝天白云，油画质感",
    ],
  },
  {
    category: "人物肖像",
    prompts: [
      "优雅的女性肖像，柔和光线，古典绘画风格",
      "智慧老者的面容，深邃眼神，素描风格",
      "天真儿童的笑容，明亮色彩，卡通风格",
      "神秘面具人物，戏剧光影，超现实主义",
    ],
  },
  {
    category: "抽象艺术",
    prompts: [
      "流动的色彩漩涡，渐变效果，抽象表现主义",
      "几何图形组合，对比色彩，现代艺术风格",
      "音乐的视觉化，律动线条，抽象派风格",
      "情感的色彩表达，自由笔触，表现主义",
    ],
  },
  {
    category: "幻想世界",
    prompts: [
      "魔法森林中的精灵，发光植物，奇幻风格",
      "漂浮的空中城堡，云海环绕，科幻艺术",
      "龙与骑士的史诗对决，史诗场景，概念艺术",
      "星空下的神秘法师，魔法光效，奇幻插画",
    ],
  },
]

const styles = [
  { value: "realistic", label: "写实风格", description: "接近真实照片的效果" },
  { value: "impressionist", label: "印象派", description: "光影变化，笔触明显" },
  { value: "abstract", label: "抽象派", description: "非具象，注重色彩和形式" },
  { value: "watercolor", label: "水彩画", description: "透明感，色彩自然融合" },
  { value: "oil-painting", label: "油画", description: "厚重质感，色彩饱满" },
  { value: "sketch", label: "素描", description: "线条勾勒，黑白灰调" },
  { value: "cartoon", label: "卡通风格", description: "简化形象，色彩鲜明" },
  { value: "anime", label: "动漫风格", description: "日式动画特色" },
]

const qualityOptions = [
  { value: "draft", label: "草图质量", description: "快速生成，适合预览" },
  { value: "standard", label: "标准质量", description: "平衡速度和质量" },
  { value: "high", label: "高质量", description: "精细细节，生成较慢" },
  { value: "ultra", label: "超高质量", description: "最佳效果，耗时最长" },
]

const aspectRatios = [
  { value: "1:1", label: "正方形 (1:1)" },
  { value: "4:3", label: "标准 (4:3)" },
  { value: "16:9", label: "宽屏 (16:9)" },
  { value: "3:4", label: "竖屏 (3:4)" },
  { value: "9:16", label: "手机 (9:16)" },
]

export default function ImageGenerationStep({ onNext, selectedImages }: ImageGenerationStepProps) {
  const [config, setConfig] = useState<GenerationConfig>({
    prompt: "",
    style: "realistic",
    creativity: 70,
    quality: "standard",
    aspectRatio: "1:1",
    steps: 30,
  })

  const [generationState, setGenerationState] = useState<GenerationState>({
    isGenerating: false,
    progress: 0,
    currentStep: "",
    phase: "idle",
  })

  const [generatedImages, setGeneratedImages] = useState<GeneratedImage[]>([])
  const [selectedCategory, setSelectedCategory] = useState(presetPrompts[0].category)
  const intervalRef = useRef<NodeJS.Timeout | null>(null)

  const updateConfig = (key: keyof GenerationConfig, value: any) => {
    if (!generationState.isGenerating) {
      setConfig((prev) => ({ ...prev, [key]: value }))
    }
  }

  const selectPresetPrompt = (prompt: string) => {
    if (!generationState.isGenerating) {
      setConfig((prev) => ({ ...prev, prompt }))
    }
  }

  const generateImage = async () => {
    if (!config.prompt.trim()) return

    setGenerationState({
      isGenerating: true,
      progress: 0,
      currentStep: "初始化生成器...",
      phase: "processing",
    })

    try {
      // 使用 Pollinations AI 免费API生成图像
      const steps = [
        { step: "解析提示词...", duration: 500 },
        { step: "连接AI服务...", duration: 800 },
        { step: "生成图像中...", duration: 2000 },
        { step: "优化图像质量...", duration: 1000 },
        { step: "完成生成...", duration: 300 },
      ]

      let totalProgress = 0
      const progressIncrement = 80 / steps.length // 留20%给实际生成

      // 模拟前期处理步骤
      for (let i = 0; i < steps.length - 1; i++) {
        setGenerationState((prev) => ({
          ...prev,
          currentStep: steps[i].step,
          phase: "processing",
        }))

        await new Promise((resolve) => setTimeout(resolve, steps[i].duration))
        totalProgress += progressIncrement
        setGenerationState((prev) => ({ ...prev, progress: totalProgress }))
      }

      // 开始实际生成
      setGenerationState((prev) => ({
        ...prev,
        currentStep: "生成图像中...",
        phase: "generating",
        progress: 80,
      }))

      // 构建API请求
      const enhancedPrompt = `${config.prompt}, ${config.style} style, high quality, detailed`
      const encodedPrompt = encodeURIComponent(enhancedPrompt)

      // 根据宽高比设置尺寸
      const dimensions = {
        "1:1": { width: 512, height: 512 },
        "4:3": { width: 512, height: 384 },
        "16:9": { width: 512, height: 288 },
        "3:4": { width: 384, height: 512 },
        "9:16": { width: 288, height: 512 },
      }
      const { width, height } = dimensions[config.aspectRatio as keyof typeof dimensions] || { width: 512, height: 512 }

      // 使用 Pollinations AI API
      const imageUrl = `https://image.pollinations.ai/prompt/${encodedPrompt}?width=${width}&height=${height}&seed=${Date.now()}&enhance=true&nologo=true`

      // 预加载图像以确保生成完成
      const img = new Image()
      img.crossOrigin = "anonymous"

      await new Promise((resolve, reject) => {
        img.onload = resolve
        img.onerror = reject
        img.src = imageUrl
      })

      setGenerationState((prev) => ({ ...prev, progress: 100 }))

      const newImage: GeneratedImage = {
        id: `img-${Date.now()}`,
        prompt: config.prompt,
        url: imageUrl,
        style: config.style,
        timestamp: new Date(),
        liked: false,
      }

      setGeneratedImages((prev) => [newImage, ...prev])
      setGenerationState({
        isGenerating: false,
        progress: 100,
        currentStep: "生成完成！",
        phase: "completed",
      })

      // 3秒后重置状态
      setTimeout(() => {
        setGenerationState((prev) => ({ ...prev, phase: "idle", progress: 0, currentStep: "" }))
      }, 3000)
    } catch (error) {
      console.error("[v0] Image generation failed:", error)
      setGenerationState({
        isGenerating: false,
        progress: 0,
        currentStep: "生成失败，请重试",
        phase: "idle",
      })
    }
  }

  const downloadImage = async (imageUrl: string, prompt: string) => {
    try {
      const response = await fetch(imageUrl)
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement("a")
      link.href = url
      link.download = `ai-artwork-${Date.now()}.png`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } catch (error) {
      console.error("[v0] Download failed:", error)
      // 如果下载失败，打开新窗口显示图像
      window.open(imageUrl, "_blank")
    }
  }

  const toggleLike = (imageId: string) => {
    setGeneratedImages((prev) => prev.map((img) => (img.id === imageId ? { ...img, liked: !img.liked } : img)))
  }

  const copyPrompt = (prompt: string) => {
    navigator.clipboard.writeText(prompt)
  }

  const getQualityTime = (quality: string) => {
    const times = { draft: "10秒", standard: "30秒", high: "60秒", ultra: "120秒" }
    return times[quality as keyof typeof times] || "30秒"
  }

  const getLearnedCategories = () => {
    const categories = {
      landscape: { name: "风景画", learned: false, count: 0 },
      portrait: { name: "人物肖像", learned: false, count: 0 },
      abstract: { name: "抽象艺术", learned: false, count: 0 },
      stilllife: { name: "静物画", learned: false, count: 0 },
    }

    // 分析选中的图像属于哪些类别
    selectedImages.forEach((imageUrl) => {
      if (
        imageUrl.includes("mountain") ||
        imageUrl.includes("landscape") ||
        imageUrl.includes("forest") ||
        imageUrl.includes("sunset") ||
        imageUrl.includes("lake") ||
        imageUrl.includes("desert")
      ) {
        categories.landscape.count++
        categories.landscape.learned = true
      }
      if (
        imageUrl.includes("portrait") ||
        imageUrl.includes("woman") ||
        imageUrl.includes("man") ||
        imageUrl.includes("child") ||
        imageUrl.includes("artist")
      ) {
        categories.portrait.count++
        categories.portrait.learned = true
      }
      if (imageUrl.includes("abstract") || imageUrl.includes("geometric") || imageUrl.includes("colorful")) {
        categories.abstract.count++
        categories.abstract.learned = true
      }
      if (
        imageUrl.includes("still-life") ||
        imageUrl.includes("floral") ||
        imageUrl.includes("fruit") ||
        imageUrl.includes("vase") ||
        imageUrl.includes("books")
      ) {
        categories.stilllife.count++
        categories.stilllife.learned = true
      }
    })

    return categories
  }

  const learnedCategories = getLearnedCategories()

  return (
    <div className="space-y-6">
      {/* Introduction */}
      <Card className="bg-chart-4/5 border-chart-4/20">
        <CardHeader>
          <div className="flex items-center gap-2">
            <Info className="w-5 h-5 text-chart-4" />
            <CardTitle className="text-lg font-serif">什么是AI图像生成？</CardTitle>
          </div>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground leading-relaxed">
            AI图像生成是人工智能的创造性应用。通过前面学习的数据和训练，AI模型已经掌握了图像的特征和规律。
            现在，你只需要用文字描述想要的画面，AI就能根据学到的知识创作出全新的艺术作品。
            这就像一位艺术家根据你的描述来绘画，但速度更快，创意无限。
          </p>
          {/* 使用提示 */}
          <div className="mt-4 p-3 bg-blue-50 rounded-lg border border-blue-200">
            <div className="flex items-start gap-2">
              <AlertCircle className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
              <p className="text-sm text-blue-800">
                <strong>使用提示：</strong>
                详细描述你想要的画面，包括主题、风格、色彩等元素，AI会根据你的描述生成独特的艺术作品。生成过程需要几秒钟时间，请耐心等待。
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Learning Status Card */}
      <Card className="bg-gradient-to-r from-green-50 to-blue-50 border-green-200">
        <CardHeader>
          <div className="flex items-center gap-2">
            <Lightbulb className="w-5 h-5 text-green-600" />
            <CardTitle className="text-lg font-serif">AI学习状态</CardTitle>
          </div>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground mb-4">
            基于你在数据采集阶段选择的 {selectedImages.length} 张图像，AI已经学习了以下艺术类别：
          </p>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {Object.entries(learnedCategories).map(([key, category]) => (
              <div
                key={key}
                className={`p-3 rounded-lg border text-center ${
                  category.learned
                    ? "bg-green-100 border-green-300 text-green-800"
                    : "bg-gray-100 border-gray-300 text-gray-600"
                }`}
              >
                <div className="font-semibold text-sm">{category.name}</div>
                <div className="text-xs mt-1">
                  {category.learned ? (
                    <>
                      <CheckCircle className="w-3 h-3 inline mr-1" />
                      已学习 ({category.count}张)
                    </>
                  ) : (
                    <>
                      <AlertCircle className="w-3 h-3 inline mr-1" />
                      未学习
                    </>
                  )}
                </div>
              </div>
            ))}
          </div>
          {Object.values(learnedCategories).some((cat) => !cat.learned) && (
            <div className="mt-4 p-3 bg-yellow-50 rounded-lg border border-yellow-200">
              <div className="flex items-start gap-2">
                <AlertCircle className="w-4 h-4 text-yellow-600 mt-0.5 flex-shrink-0" />
                <p className="text-sm text-yellow-800">
                  <strong>提示：</strong>
                  AI在未学习的类别中生成图像效果可能不如意。建议创作已学习类别的内容以获得更好的效果。
                </p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Generation Controls */}
        <Card className="lg:col-span-1">
          <CardHeader>
            <CardTitle className="font-serif">创作控制台</CardTitle>
            <CardDescription>输入提示词，调整参数，开始AI创作</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Prompt Input */}
            <div className="space-y-3">
              <Label className="font-medium">创作提示词</Label>
              <Textarea
                placeholder="描述你想要AI创作的画面，比如：宁静的山湖倒影，晨雾缭绕，水彩画风格"
                value={config.prompt}
                onChange={(e) => updateConfig("prompt", e.target.value)}
                disabled={generationState.isGenerating}
                className="min-h-20 resize-none"
              />
              <p className="text-xs text-muted-foreground">详细的描述能帮助AI更好地理解你的创意</p>
            </div>

            {/* Style Selection */}
            <div className="space-y-2">
              <Label className="font-medium">艺术风格</Label>
              <Select
                value={config.style}
                onValueChange={(value) => updateConfig("style", value)}
                disabled={generationState.isGenerating}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {styles.map((style) => (
                    <SelectItem key={style.value} value={style.value}>
                      <div>
                        <div className="font-medium">{style.label}</div>
                        <div className="text-xs text-muted-foreground">{style.description}</div>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Quality Selection */}
            <div className="space-y-2">
              <Label className="font-medium">生成质量</Label>
              <Select
                value={config.quality}
                onValueChange={(value) => updateConfig("quality", value)}
                disabled={generationState.isGenerating}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {qualityOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      <div>
                        <div className="font-medium">{option.label}</div>
                        <div className="text-xs text-muted-foreground">
                          {option.description} • 约{getQualityTime(option.value)}
                        </div>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Aspect Ratio */}
            <div className="space-y-2">
              <Label className="font-medium">画面比例</Label>
              <Select
                value={config.aspectRatio}
                onValueChange={(value) => updateConfig("aspectRatio", value)}
                disabled={generationState.isGenerating}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {aspectRatios.map((ratio) => (
                    <SelectItem key={ratio.value} value={ratio.value}>
                      {ratio.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Creativity Slider */}
            <div className="space-y-3">
              <Label className="font-medium">创意程度: {config.creativity}%</Label>
              <Slider
                value={[config.creativity]}
                onValueChange={([value]) => updateConfig("creativity", value)}
                min={0}
                max={100}
                step={10}
                disabled={generationState.isGenerating}
                className="w-full"
              />
              <div className="flex justify-between text-xs text-muted-foreground">
                <span>保守</span>
                <span>平衡</span>
                <span>创新</span>
              </div>
            </div>

            {/* Generate Button */}
            <Button
              onClick={generateImage}
              disabled={generationState.isGenerating || !config.prompt.trim()}
              className="w-full font-semibold"
              size="lg"
            >
              {generationState.isGenerating ? (
                <>
                  <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                  生成中...
                </>
              ) : (
                <>
                  <Wand2 className="w-4 h-4 mr-2" />
                  开始创作
                </>
              )}
            </Button>
          </CardContent>
        </Card>

        {/* Generation Preview and Presets */}
        <div className="lg:col-span-2 space-y-6">
          {/* Generation Status */}
          {generationState.phase !== "idle" && (
            <Card>
              <CardHeader>
                <CardTitle className="font-serif">生成进度</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex items-center gap-3">
                    <div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center">
                      {generationState.phase === "completed" ? (
                        <Sparkles className="w-4 h-4 text-primary" />
                      ) : (
                        <RefreshCw className="w-4 h-4 text-primary animate-spin" />
                      )}
                    </div>
                    <div>
                      <p className="font-medium">{generationState.currentStep}</p>
                      <p className="text-sm text-muted-foreground">
                        {generationState.phase === "completed" ? "创作完成！" : "正在处理中..."}
                      </p>
                    </div>
                  </div>
                  <Progress value={generationState.progress} className="h-2" />
                </div>
              </CardContent>
            </Card>
          )}

          {/* Preset Prompts */}
          <Card>
            <CardHeader>
              <CardTitle className="font-serif">创意提示词库</CardTitle>
              <CardDescription>选择预设提示词快速开始创作</CardDescription>
            </CardHeader>
            <CardContent>
              <Tabs value={selectedCategory} onValueChange={setSelectedCategory}>
                <TabsList className="grid w-full grid-cols-4">
                  {presetPrompts.map((category) => (
                    <TabsTrigger key={category.category} value={category.category} className="text-xs">
                      {category.category}
                    </TabsTrigger>
                  ))}
                </TabsList>

                {presetPrompts.map((category) => (
                  <TabsContent key={category.category} value={category.category} className="space-y-3 mt-4">
                    <div className="grid gap-2">
                      {category.prompts.map((prompt, index) => (
                        <button
                          key={index}
                          onClick={() => selectPresetPrompt(prompt)}
                          disabled={generationState.isGenerating}
                          className="text-left p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          <div className="flex items-start justify-between gap-2">
                            <p className="text-sm leading-relaxed">{prompt}</p>
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={(e) => {
                                e.stopPropagation()
                                copyPrompt(prompt)
                              }}
                              className="flex-shrink-0"
                            >
                              <Copy className="w-3 h-3" />
                            </Button>
                          </div>
                        </button>
                      ))}
                    </div>
                  </TabsContent>
                ))}
              </Tabs>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Generated Images Gallery */}
      {generatedImages.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="font-serif">创作作品集</CardTitle>
            <CardDescription>你的AI艺术创作历史记录</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {generatedImages.map((image) => (
                <div key={image.id} className="group relative">
                  <div className="aspect-square bg-muted rounded-lg overflow-hidden">
                    <img
                      src={image.url || "/placeholder.svg"}
                      alt={image.prompt}
                      className="w-full h-full object-cover"
                      onError={(e) => {
                        // 如果图像加载失败，显示占位符
                        const target = e.target as HTMLImageElement
                        target.src = `/placeholder.svg?height=512&width=512&query=${encodeURIComponent(image.prompt)}`
                      }}
                    />
                  </div>

                  {/* Image Overlay */}
                  <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg flex items-center justify-center">
                    <div className="flex gap-2">
                      <Button size="sm" variant="secondary" onClick={() => toggleLike(image.id)}>
                        <Heart className={`w-4 h-4 ${image.liked ? "fill-red-500 text-red-500" : ""}`} />
                      </Button>
                      <Button size="sm" variant="secondary" onClick={() => downloadImage(image.url, image.prompt)}>
                        <Download className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="secondary">
                        <Share className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>

                  {/* Image Info */}
                  <div className="mt-3 space-y-2">
                    <p className="text-sm font-medium line-clamp-2">{image.prompt}</p>
                    <div className="flex items-center justify-between text-xs text-muted-foreground">
                      <Badge variant="outline" className="text-xs">
                        {styles.find((s) => s.value === image.style)?.label}
                      </Badge>
                      <span>{image.timestamp.toLocaleTimeString()}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Completion Message */}
      <Card className="bg-primary/5 border-primary/20">
        <CardContent className="p-6">
          <div className="text-center space-y-4">
            <div className="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto">
              <Sparkles className="w-8 h-8 text-primary" />
            </div>
            <div>
              <h3 className="text-xl font-bold font-serif mb-2">恭喜完成AI绘画学习之旅！</h3>
              <p className="text-muted-foreground leading-relaxed max-w-2xl mx-auto">
                你已经完整体验了AI绘画的四个核心步骤：数据采集、数据预处理、模型训练和图像生成。
                现在你了解了AI是如何学习和创作艺术作品的。继续探索，发挥你的创意，让AI成为你的艺术创作伙伴！
              </p>
            </div>
            <div className="flex justify-center gap-4">
              <Button variant="outline" onClick={() => window.location.reload()}>
                <RefreshCw className="w-4 h-4 mr-2" />
                重新学习
              </Button>
              <Button onClick={onNext}>
                <Lightbulb className="w-4 h-4 mr-2" />
                继续创作
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
