import React, { useState } from 'react'
import { Sparkles, User, Video, Wand2, Play, Download } from 'lucide-react'
import { Project } from '../services/projectService'
import { Model } from '../services/modelService'

interface AICreationPanelProps {
  project: Project
  models: Model[]
  onMaterialCreated: () => void
}

interface CreationTask {
  id: string
  model: Model
  prompt: string
  status: 'pending' | 'processing' | 'completed' | 'failed'
  progress: number
  result?: {
    videoPath: string
    thumbnailPath: string
    duration: number
  }
  error?: string
  createdAt: Date
}

const AICreationPanel: React.FC<AICreationPanelProps> = ({
  project,
  models,
  onMaterialCreated
}) => {
  const [selectedModel, setSelectedModel] = useState<Model | null>(null)
  const [prompt, setPrompt] = useState('')
  const [creationTasks, setCreationTasks] = useState<CreationTask[]>([])
  const [isCreating, setIsCreating] = useState(false)

  const handleCreateMaterial = async () => {
    if (!selectedModel || !prompt.trim()) {
      alert('请选择模特和输入创作提示')
      return
    }

    const taskId = Date.now().toString()
    const newTask: CreationTask = {
      id: taskId,
      model: selectedModel,
      prompt: prompt.trim(),
      status: 'pending',
      progress: 0,
      createdAt: new Date()
    }

    setCreationTasks(prev => [newTask, ...prev])
    setIsCreating(true)

    try {
      // 模拟AI创作过程
      await simulateAICreation(taskId)
      
      // 创作完成后刷新素材列表
      onMaterialCreated()
    } catch (error) {
      console.error('AI creation failed:', error)
      updateTaskStatus(taskId, 'failed', 0, undefined, error instanceof Error ? error.message : '创作失败')
    } finally {
      setIsCreating(false)
    }
  }

  const simulateAICreation = async (taskId: string) => {
    // 模拟创作过程
    const steps = [
      { progress: 10, message: '初始化AI模型...' },
      { progress: 30, message: '分析模特特征...' },
      { progress: 50, message: '生成视频内容...' },
      { progress: 70, message: '渲染视频帧...' },
      { progress: 90, message: '后处理优化...' },
      { progress: 100, message: '创作完成' }
    ]

    updateTaskStatus(taskId, 'processing', 0)

    for (const step of steps) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      updateTaskStatus(taskId, 'processing', step.progress)
    }

    // 模拟创作结果
    const result = {
      videoPath: `${project.local_directory}/ai_generated_${taskId}.mp4`,
      thumbnailPath: `${project.local_directory}/ai_generated_${taskId}_thumb.jpg`,
      duration: 15
    }

    updateTaskStatus(taskId, 'completed', 100, result)
  }

  const updateTaskStatus = (
    taskId: string, 
    status: CreationTask['status'], 
    progress: number, 
    result?: CreationTask['result'],
    error?: string
  ) => {
    setCreationTasks(prev => prev.map(task => 
      task.id === taskId 
        ? { ...task, status, progress, result, error }
        : task
    ))
  }

  const getStatusColor = (status: CreationTask['status']) => {
    switch (status) {
      case 'pending':
        return 'text-yellow-600 bg-yellow-100'
      case 'processing':
        return 'text-blue-600 bg-blue-100'
      case 'completed':
        return 'text-green-600 bg-green-100'
      case 'failed':
        return 'text-red-600 bg-red-100'
      default:
        return 'text-gray-600 bg-gray-100'
    }
  }

  const getStatusText = (status: CreationTask['status']) => {
    switch (status) {
      case 'pending':
        return '等待中'
      case 'processing':
        return '创作中'
      case 'completed':
        return '已完成'
      case 'failed':
        return '失败'
      default:
        return '未知'
    }
  }

  return (
    <div className="space-y-6">
      {/* 头部说明 */}
      <div className="bg-gradient-to-r from-purple-50 to-blue-50 rounded-lg p-6">
        <div className="flex items-center mb-4">
          <Sparkles className="text-purple-600 mr-3" size={24} />
          <h3 className="text-lg font-medium text-gray-900">AI素材创作</h3>
        </div>
        <p className="text-gray-600">
          使用AI技术，基于选定的模特和创作提示，为项目"{project.product_name}"生成专属视频素材
        </p>
      </div>

      {/* 创作表单 */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <h4 className="text-md font-medium text-gray-900 mb-4">创建新素材</h4>
        
        {/* 模特选择 */}
        <div className="mb-4">
          <label className="block text-sm font-medium text-gray-700 mb-2">
            选择模特
          </label>
          {models.length === 0 ? (
            <div className="text-center py-8 bg-gray-50 rounded-lg">
              <User className="mx-auto text-gray-400 mb-2" size={32} />
              <p className="text-gray-600">请先为项目添加模特</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
              {models.map((model) => (
                <button
                  key={model.id}
                  onClick={() => setSelectedModel(model)}
                  className={`p-3 border rounded-lg text-left transition-colors ${
                    selectedModel?.id === model.id
                      ? 'border-blue-500 bg-blue-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <div className="flex items-center">
                    <User size={16} className="text-gray-400 mr-2" />
                    <div>
                      <div className="font-medium text-sm">{model.model_number}</div>
                      <div className="text-xs text-gray-500">
                        创建于 {new Date(model.created_at).toLocaleDateString()}
                      </div>
                    </div>
                  </div>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* 创作提示 */}
        <div className="mb-4">
          <label className="block text-sm font-medium text-gray-700 mb-2">
            创作提示
          </label>
          <textarea
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            placeholder={`为"${project.product_name}"创作一段展示视频，要求...`}
            rows={4}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
          />
          <p className="text-xs text-gray-500 mt-1">
            详细描述您希望AI创作的视频内容，包括场景、动作、风格等
          </p>
        </div>

        {/* 创作按钮 */}
        <button
          onClick={handleCreateMaterial}
          disabled={isCreating || !selectedModel || !prompt.trim()}
          className="flex items-center px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed"
        >
          <Wand2 size={16} className="mr-2" />
          {isCreating ? '创作中...' : '开始AI创作'}
        </button>
      </div>

      {/* 创作历史 */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <h4 className="text-md font-medium text-gray-900 mb-4">创作历史</h4>
        
        {creationTasks.length === 0 ? (
          <div className="text-center py-8 bg-gray-50 rounded-lg">
            <Video className="mx-auto text-gray-400 mb-2" size={32} />
            <p className="text-gray-600">暂无创作记录</p>
          </div>
        ) : (
          <div className="space-y-4">
            {creationTasks.map((task) => (
              <div key={task.id} className="border border-gray-200 rounded-lg p-4">
                <div className="flex items-start justify-between mb-2">
                  <div className="flex-1">
                    <div className="flex items-center mb-1">
                      <User size={14} className="text-gray-400 mr-1" />
                      <span className="text-sm font-medium">{task.model.filename}</span>
                      <span className={`ml-2 px-2 py-1 text-xs rounded-full ${getStatusColor(task.status)}`}>
                        {getStatusText(task.status)}
                      </span>
                    </div>
                    <p className="text-sm text-gray-600 mb-2">{task.prompt}</p>
                    <p className="text-xs text-gray-500">
                      {task.createdAt.toLocaleString()}
                    </p>
                  </div>
                </div>

                {/* 进度条 */}
                {task.status === 'processing' && (
                  <div className="mb-3">
                    <div className="flex items-center justify-between text-sm text-gray-600 mb-1">
                      <span>创作进度</span>
                      <span>{task.progress}%</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div 
                        className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                        style={{ width: `${task.progress}%` }}
                      ></div>
                    </div>
                  </div>
                )}

                {/* 错误信息 */}
                {task.status === 'failed' && task.error && (
                  <div className="mb-3 p-2 bg-red-50 border border-red-200 rounded text-sm text-red-600">
                    {task.error}
                  </div>
                )}

                {/* 结果操作 */}
                {task.status === 'completed' && task.result && (
                  <div className="flex items-center space-x-2">
                    <button className="flex items-center px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors">
                      <Play size={14} className="mr-1" />
                      预览
                    </button>
                    <button className="flex items-center px-3 py-1 bg-green-600 text-white text-sm rounded hover:bg-green-700 transition-colors">
                      <Download size={14} className="mr-1" />
                      下载
                    </button>
                    <span className="text-xs text-gray-500">
                      时长: {task.result.duration}s
                    </span>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export default AICreationPanel
