import React from 'react';
import {
  ClockIcon,
  CheckCircleIcon,
  ExclamationCircleIcon,
  XCircleIcon,
  PlayIcon,
  PauseIcon,
  TrashIcon
} from '@heroicons/react/24/outline';

export interface VideoGenerationTask {
  id: string;
  name: string;
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
  progress: number; // 0-100
  startTime?: string;
  endTime?: string;
  duration?: number;
  errorMessage?: string;
  outputPath?: string;
}

interface TaskStatusPanelProps {
  tasks: VideoGenerationTask[];
  onCancelTask?: (taskId: string) => void;
  onRetryTask?: (taskId: string) => void;
  onDeleteTask?: (taskId: string) => void;
}

/**
 * 任务状态面板组件
 * 显示视频生成任务的运行状况
 */
export const TaskStatusPanel: React.FC<TaskStatusPanelProps> = ({
  tasks,
  onCancelTask,
  onRetryTask,
  onDeleteTask
}) => {
  const getStatusIcon = (status: VideoGenerationTask['status']) => {
    switch (status) {
      case 'pending':
        return <ClockIcon className="h-4 w-4 text-yellow-500" />;
      case 'running':
        return <PlayIcon className="h-4 w-4 text-blue-500" />;
      case 'completed':
        return <CheckCircleIcon className="h-4 w-4 text-green-500" />;
      case 'failed':
        return <XCircleIcon className="h-4 w-4 text-red-500" />;
      case 'cancelled':
        return <PauseIcon className="h-4 w-4 text-gray-500" />;
      default:
        return <ClockIcon className="h-4 w-4 text-gray-400" />;
    }
  };

  const getStatusText = (status: VideoGenerationTask['status']) => {
    switch (status) {
      case 'pending':
        return '等待中';
      case 'running':
        return '运行中';
      case 'completed':
        return '已完成';
      case 'failed':
        return '失败';
      case 'cancelled':
        return '已取消';
      default:
        return '未知';
    }
  };

  const getStatusColor = (status: VideoGenerationTask['status']) => {
    switch (status) {
      case 'pending':
        return 'bg-yellow-50 border-yellow-200';
      case 'running':
        return 'bg-blue-50 border-blue-200';
      case 'completed':
        return 'bg-green-50 border-green-200';
      case 'failed':
        return 'bg-red-50 border-red-200';
      case 'cancelled':
        return 'bg-gray-50 border-gray-200';
      default:
        return 'bg-gray-50 border-gray-200';
    }
  };

  const formatDuration = (seconds?: number) => {
    if (!seconds) return '';
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const formatTime = (timeString?: string) => {
    if (!timeString) return '';
    const date = new Date(timeString);
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit',
      second: '2-digit'
    });
  };

  return (
    <div className="h-full flex flex-col">
      {/* 任务统计 */}
      <div className="flex-shrink-0 p-3 border-b border-gray-200">
        <div className="grid grid-cols-2 gap-2 text-xs">
          <div className="text-center">
            <div className="font-medium text-gray-900">
              {tasks.filter(t => t.status === 'running').length}
            </div>
            <div className="text-gray-500">运行中</div>
          </div>
          <div className="text-center">
            <div className="font-medium text-gray-900">
              {tasks.filter(t => t.status === 'pending').length}
            </div>
            <div className="text-gray-500">等待中</div>
          </div>
        </div>
      </div>

      {/* 任务列表 */}
      <div className="flex-1 overflow-y-auto custom-scrollbar">
        {tasks.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full text-gray-500 p-4">
            <ClockIcon className="h-8 w-8 mb-2 text-gray-300" />
            <div className="text-sm text-center">暂无运行任务</div>
            <div className="text-xs text-center mt-1">
              点击"开始生成"创建任务
            </div>
          </div>
        ) : (
          <div className="p-3 space-y-3">
            {tasks.map((task) => (
              <div
                key={task.id}
                className={`p-3 rounded-lg border transition-all duration-200 ${getStatusColor(task.status)}`}
              >
                {/* 任务标题和状态 */}
                <div className="flex items-start justify-between mb-2">
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium text-gray-900 truncate">
                      {task.name}
                    </div>
                    <div className="flex items-center gap-1 mt-1">
                      {getStatusIcon(task.status)}
                      <span className="text-xs text-gray-600">
                        {getStatusText(task.status)}
                      </span>
                    </div>
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex items-center gap-1 ml-2">
                    {task.status === 'running' && onCancelTask && (
                      <button
                        onClick={() => onCancelTask(task.id)}
                        className="p-1 text-gray-400 hover:text-red-600 rounded"
                        title="取消任务"
                      >
                        <PauseIcon className="h-3 w-3" />
                      </button>
                    )}
                    {task.status === 'failed' && onRetryTask && (
                      <button
                        onClick={() => onRetryTask(task.id)}
                        className="p-1 text-gray-400 hover:text-blue-600 rounded"
                        title="重试任务"
                      >
                        <PlayIcon className="h-3 w-3" />
                      </button>
                    )}
                    {(task.status === 'completed' || task.status === 'failed' || task.status === 'cancelled') && onDeleteTask && (
                      <button
                        onClick={() => onDeleteTask(task.id)}
                        className="p-1 text-gray-400 hover:text-red-600 rounded"
                        title="删除任务"
                      >
                        <TrashIcon className="h-3 w-3" />
                      </button>
                    )}
                  </div>
                </div>

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

                {/* 任务详情 */}
                <div className="text-xs text-gray-500 space-y-1">
                  {task.startTime && (
                    <div>开始: {formatTime(task.startTime)}</div>
                  )}
                  {task.endTime && (
                    <div>结束: {formatTime(task.endTime)}</div>
                  )}
                  {task.duration && (
                    <div>耗时: {formatDuration(task.duration)}</div>
                  )}
                  {task.status === 'failed' && task.errorMessage && (
                    <div className="text-red-600 mt-1">
                      <ExclamationCircleIcon className="h-3 w-3 inline mr-1" />
                      {task.errorMessage}
                    </div>
                  )}
                  {task.status === 'completed' && task.outputPath && (
                    <div className="text-green-600 mt-1">
                      <CheckCircleIcon className="h-3 w-3 inline mr-1" />
                      输出: {task.outputPath.split('/').pop()}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 底部操作 */}
      <div className="flex-shrink-0 p-3 border-t border-gray-200">
        <button
          onClick={() => {
            const completedTasks = tasks.filter(t => t.status === 'completed' || t.status === 'failed' || t.status === 'cancelled');
            completedTasks.forEach(task => onDeleteTask?.(task.id));
          }}
          disabled={!tasks.some(t => t.status === 'completed' || t.status === 'failed' || t.status === 'cancelled')}
          className="w-full px-3 py-2 text-xs text-gray-600 border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
        >
          清理已完成任务
        </button>
      </div>
    </div>
  );
};
