/**
 * Text Video Generator Component
 * 使用 Text Video Agent API 的 React 组件示例
 */

import React, { useState, useCallback } from 'react'
import { 
  Upload, 
  Image, 
  Video, 
  Loader, 
  AlertCircle, 
  CheckCircle, 
  Play,
  Download,
  RefreshCw
} from 'lucide-react'

import { useTextVideoAgent, useTaskPolling } from '../hooks/useTextVideoAgent'
import { TaskType, AspectRatio, VideoDuration } from '../services/textVideoAgentTypes'

interface TextVideoGeneratorProps {
  onImageGenerated?: (imageUrl: string) => void
  onVideoGenerated?: (videoUrl: string) => void
}

const TextVideoGenerator: React.FC<TextVideoGeneratorProps> = ({
  onImageGenerated,
  onVideoGenerated
}) => {
  // Hook状态
  const {
    state,
    generateImage,
    generateVideo,
    generateContentEndToEnd,
    uploadFile,
    describeImageByFile,
    reset,
    cancel
  } = useTextVideoAgent()

  // 本地状态
  const [prompt, setPrompt] = useState('')
  const [taskType, setTaskType] = useState<TaskType>(TaskType.VLOG)
  const [aspectRatio, setAspectRatio] = useState<AspectRatio>(AspectRatio.PORTRAIT)
  const [videoDuration, setVideoDuration] = useState<VideoDuration>(VideoDuration.MEDIUM)
  const [referenceFile, setReferenceFile] = useState<File | null>(null)
  const [generateVideoEnabled, setGenerateVideoEnabled] = useState(false)
  const [results, setResults] = useState<{
    imageUrl?: string
    videoUrl?: string
    taskId?: string
  }>({})

  // 处理文件上传
  const handleFileUpload = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    setReferenceFile(file)

    // 自动分析图片内容
    try {
      const description = await describeImageByFile(file)
      if (description) {
        setPrompt(prev => prev ? `${prev}\n\n参考图片描述: ${description}` : description)
      }
    } catch (error) {
      console.error('图片分析失败:', error)
    }
  }, [describeImageByFile])

  // 生成内容
  const handleGenerate = useCallback(async () => {
    if (!prompt.trim()) {
      alert('请输入生成提示词')
      return
    }

    try {
      const result = await generateContentEndToEnd(prompt, {
        taskType,
        aspectRatio,
        videoDuration,
        generateVideo: generateVideoEnabled
      })

      if (result) {
        setResults(result)
        
        if (result.imageUrl && onImageGenerated) {
          onImageGenerated(result.imageUrl)
        }
        
        if (result.videoUrl && onVideoGenerated) {
          onVideoGenerated(result.videoUrl)
        }
      }
    } catch (error) {
      console.error('生成失败:', error)
    }
  }, [
    prompt,
    taskType,
    aspectRatio,
    videoDuration,
    generateVideoEnabled,
    generateContentEndToEnd,
    onImageGenerated,
    onVideoGenerated
  ])

  // 只生成图片
  const handleGenerateImageOnly = useCallback(async () => {
    if (!prompt.trim()) {
      alert('请输入生成提示词')
      return
    }

    try {
      const imageUrl = await generateImage({
        prompt,
        img_file: referenceFile || undefined,
        max_wait_time: 120
      })

      if (imageUrl) {
        setResults(prev => ({ ...prev, imageUrl }))
        onImageGenerated?.(imageUrl)
      }
    } catch (error) {
      console.error('图片生成失败:', error)
    }
  }, [prompt, referenceFile, generateImage, onImageGenerated])

  // 基于图片生成视频
  const handleGenerateVideoFromImage = useCallback(async () => {
    if (!results.imageUrl) {
      alert('请先生成图片')
      return
    }

    try {
      const videoUrl = await generateVideo({
        prompt,
        img_url: results.imageUrl,
        duration: videoDuration,
        max_wait_time: 300
      })

      if (videoUrl) {
        setResults(prev => ({ ...prev, videoUrl }))
        onVideoGenerated?.(videoUrl)
      }
    } catch (error) {
      console.error('视频生成失败:', error)
    }
  }, [results.imageUrl, prompt, videoDuration, generateVideo, onVideoGenerated])

  // 重置所有状态
  const handleReset = useCallback(() => {
    reset()
    setPrompt('')
    setReferenceFile(null)
    setResults({})
  }, [reset])

  return (
    <div className="max-w-4xl mx-auto p-6 bg-white rounded-lg shadow-lg">
      {/* 标题 */}
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-900 mb-2">AI 内容生成器</h2>
        <p className="text-gray-600">基于 Text Video Agent API 的智能内容生成工具</p>
      </div>

      {/* 输入区域 */}
      <div className="space-y-6">
        {/* 提示词输入 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            生成提示词 *
          </label>
          <textarea
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            placeholder="描述您想要生成的内容..."
            rows={4}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            disabled={state.isLoading}
          />
        </div>

        {/* 参数配置 */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              任务类型
            </label>
            <select
              value={taskType}
              onChange={(e) => setTaskType(e.target.value as TaskType)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500"
              disabled={state.isLoading}
            >
              <option value={TaskType.VLOG}>Vlog</option>
              <option value={TaskType.TEA}>茶文化</option>
              <option value={TaskType.LADY}>人物</option>
              <option value={TaskType.CHOP}>烹饪</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              长宽比
            </label>
            <select
              value={aspectRatio}
              onChange={(e) => setAspectRatio(e.target.value as AspectRatio)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500"
              disabled={state.isLoading}
            >
              <option value={AspectRatio.PORTRAIT}>9:16 (竖屏)</option>
              <option value={AspectRatio.LANDSCAPE}>16:9 (横屏)</option>
              <option value={AspectRatio.SQUARE}>1:1 (方形)</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              视频时长
            </label>
            <select
              value={videoDuration}
              onChange={(e) => setVideoDuration(e.target.value as VideoDuration)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500"
              disabled={state.isLoading}
            >
              <option value={VideoDuration.SHORT}>3秒</option>
              <option value={VideoDuration.MEDIUM}>5秒</option>
              <option value={VideoDuration.LONG}>10秒</option>
            </select>
          </div>
        </div>

        {/* 参考图片上传 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            参考图片 (可选)
          </label>
          <div className="flex items-center space-x-4">
            <label className="flex items-center px-4 py-2 bg-gray-100 text-gray-700 rounded-md cursor-pointer hover:bg-gray-200 transition-colors">
              <Upload size={16} className="mr-2" />
              选择文件
              <input
                type="file"
                accept="image/*"
                onChange={handleFileUpload}
                className="hidden"
                disabled={state.isLoading}
              />
            </label>
            {referenceFile && (
              <span className="text-sm text-gray-600">
                {referenceFile.name}
              </span>
            )}
          </div>
        </div>

        {/* 生成选项 */}
        <div>
          <label className="flex items-center">
            <input
              type="checkbox"
              checked={generateVideoEnabled}
              onChange={(e) => setGenerateVideoEnabled(e.target.checked)}
              className="mr-2"
              disabled={state.isLoading}
            />
            <span className="text-sm text-gray-700">同时生成视频</span>
          </label>
        </div>
      </div>

      {/* 状态显示 */}
      {state.isLoading && (
        <div className="mt-6 p-4 bg-blue-50 rounded-md">
          <div className="flex items-center">
            <Loader className="animate-spin mr-2 text-blue-600" size={16} />
            <span className="text-blue-800">{state.currentStep}</span>
          </div>
          {state.progress > 0 && (
            <div className="mt-2">
              <div className="w-full bg-blue-200 rounded-full h-2">
                <div 
                  className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${state.progress}%` }}
                />
              </div>
              <span className="text-xs text-blue-600 mt-1">{state.progress}%</span>
            </div>
          )}
        </div>
      )}

      {/* 错误显示 */}
      {state.error && (
        <div className="mt-6 p-4 bg-red-50 rounded-md">
          <div className="flex items-center">
            <AlertCircle className="mr-2 text-red-600" size={16} />
            <span className="text-red-800">{state.error}</span>
          </div>
        </div>
      )}

      {/* 操作按钮 */}
      <div className="mt-6 flex flex-wrap gap-3">
        <button
          onClick={handleGenerate}
          disabled={state.isLoading || !prompt.trim()}
          className="flex items-center px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
        >
          {state.isLoading ? (
            <Loader className="animate-spin mr-2" size={16} />
          ) : (
            <Play className="mr-2" size={16} />
          )}
          {generateVideoEnabled ? '生成图片和视频' : '生成内容'}
        </button>

        <button
          onClick={handleGenerateImageOnly}
          disabled={state.isLoading || !prompt.trim()}
          className="flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
        >
          <Image className="mr-2" size={16} />
          仅生成图片
        </button>

        {results.imageUrl && (
          <button
            onClick={handleGenerateVideoFromImage}
            disabled={state.isLoading}
            className="flex items-center px-4 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
          >
            <Video className="mr-2" size={16} />
            基于图片生成视频
          </button>
        )}

        {state.isLoading && (
          <button
            onClick={cancel}
            className="flex items-center px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors"
          >
            取消
          </button>
        )}

        <button
          onClick={handleReset}
          disabled={state.isLoading}
          className="flex items-center px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
        >
          <RefreshCw className="mr-2" size={16} />
          重置
        </button>
      </div>

      {/* 结果显示 */}
      {(results.imageUrl || results.videoUrl) && (
        <div className="mt-8 space-y-6">
          <h3 className="text-lg font-semibold text-gray-900">生成结果</h3>
          
          {/* 图片结果 */}
          {results.imageUrl && (
            <div className="bg-gray-50 p-4 rounded-md">
              <div className="flex items-center justify-between mb-3">
                <h4 className="font-medium text-gray-900 flex items-center">
                  <Image className="mr-2" size={16} />
                  生成的图片
                </h4>
                <a
                  href={results.imageUrl}
                  download
                  className="flex items-center text-blue-600 hover:text-blue-700"
                >
                  <Download size={16} className="mr-1" />
                  下载
                </a>
              </div>
              <img
                src={results.imageUrl}
                alt="Generated"
                className="max-w-full h-auto rounded-md shadow-sm"
              />
            </div>
          )}

          {/* 视频结果 */}
          {results.videoUrl && (
            <div className="bg-gray-50 p-4 rounded-md">
              <div className="flex items-center justify-between mb-3">
                <h4 className="font-medium text-gray-900 flex items-center">
                  <Video className="mr-2" size={16} />
                  生成的视频
                </h4>
                <a
                  href={results.videoUrl}
                  download
                  className="flex items-center text-blue-600 hover:text-blue-700"
                >
                  <Download size={16} className="mr-1" />
                  下载
                </a>
              </div>
              <video
                src={results.videoUrl}
                controls
                className="max-w-full h-auto rounded-md shadow-sm"
              >
                您的浏览器不支持视频播放
              </video>
            </div>
          )}
        </div>
      )}
    </div>
  )
}

export default TextVideoGenerator
