import React, { useState } from 'react'
import { Play } from 'lucide-react'
import { useAIVideoStore, useAIVideoJobs, useAIVideoProcessing, useAIVideoSettings } from '../stores/useAIVideoStore'
import AIVideoResultPreview from './AIVideoResultPreview'
import VideoModeSelector from './ai-video/VideoModeSelector'
import SingleVideoForm from './ai-video/SingleVideoForm'
import BatchVideoForm from './ai-video/BatchVideoForm'
import VideoSettings from './ai-video/VideoSettings'
import VideoJobList from './ai-video/VideoJobList'

interface AIVideoGeneratorProps {
  className?: string
}

const AIVideoGenerator: React.FC<AIVideoGeneratorProps> = ({ className = '' }) => {
  // State
  const [mode, setMode] = useState<'single' | 'batch'>('single')
  const [selectedImage, setSelectedImage] = useState<string>('')
  const [selectedFolder, setSelectedFolder] = useState<string>('')
  const [customPrompt, setCustomPrompt] = useState<string>('')
  const [batchPrompts, setBatchPrompts] = useState<string[]>([''])
  const [outputFolder, setOutputFolder] = useState<string>('')
  const [singleOutputFolder, setSingleOutputFolder] = useState<string>('')
  const [duration, setDuration] = useState<string>('5')
  const [modelType, setModelType] = useState<string>('lite')
  const [previewData, setPreviewData] = useState<{
    isOpen: boolean
    result: any
    jobType: 'single' | 'batch'
    prompt?: string
    imagePath?: string
  }>({
    isOpen: false,
    result: null,
    jobType: 'single'
  })
  
  // Store hooks
  const jobs = useAIVideoJobs()
  const isProcessing = useAIVideoProcessing()
  const { defaultDuration, defaultModelType } = useAIVideoSettings()

  // Store actions
  const generateSingleVideo = useAIVideoStore(state => state.generateSingleVideo)
  const batchGenerateVideos = useAIVideoStore(state => state.batchGenerateVideos)
  const clearCompletedJobs = useAIVideoStore(state => state.clearCompletedJobs)
  const removeJob = useAIVideoStore(state => state.removeJob)

  // Initialize settings
  React.useEffect(() => {
    setDuration(defaultDuration)
    setModelType(defaultModelType)
  }, [defaultDuration, defaultModelType])

  // Preview functions
  const openPreview = (job: any) => {
    setPreviewData({
      isOpen: true,
      result: job.result,
      jobType: job.type,
      prompt: job.type === 'single' ? job.request.prompt : undefined,
      imagePath: job.type === 'single' ? job.request.imagePath : undefined
    })
  }

  const closePreview = () => {
    setPreviewData({
      isOpen: false,
      result: null,
      jobType: 'single'
    })
  }

  // Delete job function
  const deleteJob = (jobId: string) => {
    removeJob(jobId)
  }

  // Retry job function
  const handleRetryJob = async (job: any) => {
    try {
      if (job.type === 'single') {
        await generateSingleVideo(job.request)
      } else if (job.type === 'batch') {
        await batchGenerateVideos(job.request)
      }
    } catch (error) {
      console.error('Retry failed:', error)
      alert(`重试失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  // Handle generation
  const handleGenerate = async () => {
    try {
      if (mode === 'single') {
        if (!selectedImage || !customPrompt) {
          alert('请选择图片文件并输入提示词')
          return
        }

        await generateSingleVideo({
          image_path: selectedImage,
          prompt: customPrompt,
          duration,
          model_type: modelType,
          output_path: singleOutputFolder || undefined,
          timeout: 300
        })
      } else {
        if (!selectedFolder || !outputFolder) {
          alert('请选择图片文件夹和输出目录')
          return
        }

        const prompts = batchPrompts.filter(p => p.trim()).length > 0
          ? batchPrompts.filter(p => p.trim())
          : ['默认提示词']

        await batchGenerateVideos({
          image_folder: selectedFolder,
          prompts,
          output_folder: outputFolder,
          duration,
          model_type: modelType,
          timeout: 300
        })
      }
    } catch (error) {
      console.error('Generation failed:', error)
      alert(`生成失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  return (
    <div className={`bg-white rounded-lg shadow-sm border border-secondary-200 ${className}`}>
      {/* Header */}
      <div className="p-6 border-b border-secondary-200">
        <h2 className="text-xl font-semibold text-secondary-900 mb-4">AI 视频生成</h2>
        
        {/* Mode Selection */}
        <div className="mb-6">
          <VideoModeSelector mode={mode} onModeChange={setMode} />
        </div>

        {/* Form Section */}
        <div className="space-y-6">
          {mode === 'single' ? (
            <SingleVideoForm
              selectedImage={selectedImage}
              onImageChange={setSelectedImage}
              customPrompt={customPrompt}
              onPromptChange={setCustomPrompt}
              singleOutputFolder={singleOutputFolder}
              onOutputFolderChange={setSingleOutputFolder}
            />
          ) : (
            <BatchVideoForm
              selectedFolder={selectedFolder}
              onFolderChange={setSelectedFolder}
              batchPrompts={batchPrompts}
              onPromptsChange={setBatchPrompts}
              outputFolder={outputFolder}
              onOutputFolderChange={setOutputFolder}
            />
          )}

          {/* Video Settings */}
          <VideoSettings
            duration={duration}
            onDurationChange={setDuration}
            modelType={modelType}
            onModelTypeChange={setModelType}
          />
        </div>
        
        {/* Generate Button */}
        <button
          onClick={handleGenerate}
          disabled={isProcessing}
          className="btn-primary w-full py-3 disabled:opacity-50 disabled:cursor-not-allowed mt-6"
        >
          <Play size={16} className="mr-2" />
          {isProcessing ? '生成中...' : '开始生成'}
        </button>
      </div>
      {/* Video Preview Modal */}
      <AIVideoResultPreview
        isOpen={previewData.isOpen}
        onClose={closePreview}
        result={previewData.result}
        jobType={previewData.jobType}
        prompt={previewData.prompt}
        imagePath={previewData.imagePath}
      />
    </div>
  )
}

export default AIVideoGenerator
