import React, { useState } from 'react'
import { Play, Trash2, Copy, Check, RotateCcw } from 'lucide-react'

interface VideoJob {
  id: string
  type: 'single' | 'batch'
  status: 'pending' | 'processing' | 'completed' | 'failed'
  progress: number
  request: any
  result?: any
  error?: string
  startTime: number
  endTime?: number
  progressLogs?: string[]
  currentStep?: string
}

interface VideoJobListProps {
  jobs: VideoJob[]
  onPreview: (job: VideoJob) => void
  onDelete: (jobId: string) => void
  onRetry: (job: VideoJob) => void
}

const VideoJobList: React.FC<VideoJobListProps> = ({ jobs, onPreview, onDelete, onRetry }) => {
  const [copiedJobId, setCopiedJobId] = useState<string | null>(null)

  const formatTime = (timestamp: number): string => {
    return new Date(timestamp).toLocaleTimeString()
  }

  const getStatusColor = (status: string): string => {
    switch (status) {
      case 'processing': return 'text-blue-600'
      case 'completed': return 'text-green-600'
      case 'failed': return 'text-red-600'
      default: return 'text-gray-600'
    }
  }

  const getStatusText = (status: string): string => {
    switch (status) {
      case 'pending': return '等待中'
      case 'processing': return '处理中'
      case 'completed': return '已完成'
      case 'failed': return '失败'
      default: return '未知'
    }
  }

  const copyErrorToClipboard = (job: VideoJob) => {
    const errorInfo = {
      error: job.error,
      request: job.request,
      id: job.id,
      status: job.status,
      startTime: new Date(job.startTime).toLocaleString(),
      endTime: job.endTime ? new Date(job.endTime).toLocaleString() : undefined
    }

    navigator.clipboard.writeText(JSON.stringify(errorInfo, null, 2))
      .then(() => {
        setCopiedJobId(job.id)
        setTimeout(() => setCopiedJobId(null), 2000)
      })
      .catch(err => console.error('Failed to copy error info:', err))
  }

  if (jobs.length === 0) {
    return (
      <div className="text-center py-8 text-gray-500">
        暂无任务
      </div>
    )
  }

  return (
    <div className="space-y-3">
      {jobs.slice().reverse().map(job => (
        <div
          key={job.id}
          className="border border-secondary-200 rounded-lg p-4 bg-white hover:bg-secondary-50 transition-colors"
        >
          {/* Job Header */}
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center space-x-2">
              <span className="text-xs font-medium text-secondary-700">
                {job.type === 'single' ? '单个' : '批量'}
              </span>
              <span className={`text-xs font-medium ${getStatusColor(job.status)}`}>
                {getStatusText(job.status)}
              </span>
            </div>
            <div className="flex items-center space-x-2">
              <span className="text-xs text-secondary-500">
                {formatTime(job.startTime)}
              </span>
              <button
                onClick={() => onDelete(job.id)}
                className="text-red-500 hover:text-red-700 transition-colors"
                title="删除任务"
              >
                <Trash2 size={14} />
              </button>
            </div>
          </div>

          {/* Progress Bar */}
          {job.status === 'processing' && (
            <div className="mb-2">
              <div className="w-full bg-secondary-200 rounded-full h-2">
                <div 
                  className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${job.progress}%` }}
                />
              </div>
              <div className="text-xs text-secondary-600 mt-1">
                {job.progress}% 完成
              </div>
              {job.currentStep && (
                <div className="text-xs text-blue-600 mt-1">
                  {job.currentStep}
                </div>
              )}
              {job.progressLogs && job.progressLogs.length > 0 && (
                <div className="mt-2 max-h-20 overflow-y-auto bg-gray-50 p-2 rounded text-xs">
                  {job.progressLogs.slice(-3).map((log, index) => (
                    <div key={index} className="text-gray-600 mb-1">
                      {log}
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Success Result */}
          {job.result && job.status === 'completed' && (
            <div className="text-sm text-green-600 bg-green-50 p-3 rounded">
              <div className="flex items-center justify-between">
                <div>
                  <div className="font-medium mb-1">✅ 生成成功！</div>
                  {job.type === 'batch' && job.result.success_count && (
                    <div className="text-xs text-green-600">
                      成功: {job.result.success_count} 个，失败: {job.result.failed_count || 0} 个
                    </div>
                  )}
                </div>
                {(job.result.video_path || job.result.video_url || job.result.results) && (
                  <button 
                    onClick={() => onPreview(job)}
                    className="flex items-center gap-1 px-3 py-1 bg-blue-600 text-white text-xs rounded hover:bg-blue-700 transition-colors"
                  >
                    <Play size={12} />
                    预览视频
                  </button>
                )}
              </div>
            </div>
          )}

          {/* Error Result */}
          {job.error && job.status === 'failed' && (
            <div className="text-sm text-red-600 bg-red-50 p-3 rounded">
              <div className="flex items-center justify-between mb-2">
                <div className="font-medium">❌ 生成失败</div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => onRetry(job)}
                    className="flex items-center gap-1 px-2 py-1 bg-blue-600 text-white text-xs rounded hover:bg-blue-700 transition-colors"
                    title="重试任务"
                  >
                    <RotateCcw size={12} />
                    重试
                  </button>
                  <button
                    onClick={() => copyErrorToClipboard(job)}
                    className="flex items-center gap-1 px-2 py-1 bg-red-600 text-white text-xs rounded hover:bg-red-700 transition-colors"
                    title="复制错误信息"
                  >
                    {copiedJobId === job.id ? (
                      <>
                        <Check size={12} />
                        已复制
                      </>
                    ) : (
                      <>
                        <Copy size={12} />
                        复制
                      </>
                    )}
                  </button>
                </div>
              </div>
              <div className="text-xs text-red-700 mb-2">
                错误信息: {job.error}
              </div>
              <details className="text-xs">
                <summary className="cursor-pointer text-red-600 hover:text-red-800">
                  查看详细信息
                </summary>
                <pre className="mt-2 p-2 bg-red-100 rounded text-xs overflow-auto max-h-32">
                  {JSON.stringify(job, null, 2)}
                </pre>
              </details>
            </div>
          )}
        </div>
      ))}
    </div>
  )
}

export default VideoJobList
