import React from 'react';
import {
  Play,
  Pause,
  Square,
  Trash2,
  Clock,
  CheckCircle,
  AlertCircle,
  FileVideo
} from 'lucide-react';
import {
  BatchThumbnailTask,
  TaskStatus,
  TASK_STATUS_LABELS,
  TASK_STATUS_COLORS
} from '../../types/thumbnail';

interface TaskListProps {
  tasks: BatchThumbnailTask[];
  onCancel: (taskId: string) => void;
  onPause: (taskId: string) => void;
  onResume: (taskId: string) => void;
  onCleanup: () => void;
}

/**
 * 任务列表组件
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
export const TaskList: React.FC<TaskListProps> = ({
  tasks,
  onCancel,
  onPause,
  onResume,
  onCleanup,
}) => {
  // 按状态分组任务
  const groupedTasks = React.useMemo(() => {
    const groups: Record<TaskStatus, BatchThumbnailTask[]> = {
      [TaskStatus.Running]: [],
      [TaskStatus.Paused]: [],
      [TaskStatus.Pending]: [],
      [TaskStatus.Completed]: [],
      [TaskStatus.Failed]: [],
      [TaskStatus.Cancelled]: [],
    };

    tasks.forEach(task => {
      groups[task.status].push(task);
    });

    return groups;
  }, [tasks]);

  // 获取状态颜色
  const getStatusColor = (status: TaskStatus): string => {
    return TASK_STATUS_COLORS[status] || 'text-gray-600 bg-gray-50';
  };

  // 渲染任务项
  const renderTask = (task: BatchThumbnailTask) => {
    const { progress } = task;
    const canControl = task.status === TaskStatus.Running || task.status === TaskStatus.Paused;

    return (
      <div key={task.task_id} className="p-4 bg-white border border-gray-200 rounded-lg">
        {/* 任务头部 */}
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <div className="flex-shrink-0">
              <FileVideo className="w-5 h-5 text-blue-500" />
            </div>
            <div>
              <h4 className="text-sm font-medium text-gray-900">
                批量缩略图任务
              </h4>
              <p className="text-xs text-gray-500">
                {task.video_files.length} 个文件 • {task.task_id.slice(0, 8)}...
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(task.status)}`}>
              {TASK_STATUS_LABELS[task.status]}
            </span>

            {canControl && (
              <div className="flex gap-1">
                {task.status === TaskStatus.Running && (
                  <button
                    onClick={() => onPause(task.task_id)}
                    className="p-1 text-orange-500 hover:text-orange-700 hover:bg-orange-50 rounded transition-colors"
                    title="暂停"
                  >
                    <Pause className="w-3 h-3" />
                  </button>
                )}
                {task.status === TaskStatus.Paused && (
                  <button
                    onClick={() => onResume(task.task_id)}
                    className="p-1 text-green-500 hover:text-green-700 hover:bg-green-50 rounded transition-colors"
                    title="恢复"
                  >
                    <Play className="w-3 h-3" />
                  </button>
                )}
                <button
                  onClick={() => onCancel(task.task_id)}
                  className="p-1 text-red-500 hover:text-red-700 hover:bg-red-50 rounded transition-colors"
                  title="取消"
                >
                  <Square className="w-3 h-3" />
                </button>
              </div>
            )}
          </div>
        </div>

        {/* 进度信息 */}
        {task.status !== TaskStatus.Pending && (
          <div className="space-y-2">
            <div className="flex items-center justify-between text-xs">
              <span className="text-gray-600">
                {progress.processed_files + progress.failed_files} / {progress.total_files}
              </span>
              <span className="font-medium">
                {progress.progress_percentage.toFixed(1)}%
              </span>
            </div>

            <div className="w-full bg-gray-200 rounded-full h-2">
              <div
                className={`h-2 rounded-full transition-all duration-300 ${
                  task.status === TaskStatus.Completed
                    ? 'bg-green-500'
                    : task.status === TaskStatus.Failed
                    ? 'bg-red-500'
                    : 'bg-blue-500'
                }`}
                style={{ width: `${progress.progress_percentage}%` }}
              />
            </div>

            <div className="flex items-center justify-between text-xs text-gray-500">
              <div className="flex items-center gap-3">
                <span className="flex items-center gap-1">
                  <CheckCircle className="w-3 h-3 text-green-500" />
                  {progress.processed_files}
                </span>
                {progress.failed_files > 0 && (
                  <span className="flex items-center gap-1">
                    <AlertCircle className="w-3 h-3 text-red-500" />
                    {progress.failed_files}
                  </span>
                )}
              </div>

              <div className="flex items-center gap-1">
                <Clock className="w-3 h-3" />
                {new Date(task.updated_at).toLocaleTimeString()}
              </div>
            </div>
          </div>
        )}

        {/* 当前处理文件 */}
        {progress.current_file && task.status === TaskStatus.Running && (
          <div className="mt-3 p-2 bg-blue-50 rounded text-xs">
            <span className="text-blue-600">正在处理: </span>
            <span className="text-blue-800 font-medium">
              {progress.current_file.split(/[/\\]/).pop()}
            </span>
          </div>
        )}

        {/* 错误信息 */}
        {progress.errors.length > 0 && (
          <div className="mt-3 p-2 bg-red-50 rounded">
            <div className="text-xs text-red-600 font-medium mb-1">
              错误 ({progress.errors.length})
            </div>
            <div className="text-xs text-red-500">
              {progress.errors[progress.errors.length - 1]}
            </div>
          </div>
        )}
      </div>
    );
  };

  // 渲染任务组
  const renderTaskGroup = (status: TaskStatus, tasks: BatchThumbnailTask[]) => {
    if (tasks.length === 0) return null;

    return (
      <div key={status} className="space-y-3">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-medium text-gray-700 flex items-center gap-2">
            <span className={`w-2 h-2 rounded-full ${getStatusColor(status).split(' ')[1]}`} />
            {TASK_STATUS_LABELS[status]} ({tasks.length})
          </h3>
        </div>
        <div className="space-y-3">
          {tasks.map(renderTask)}
        </div>
      </div>
    );
  };

  if (tasks.length === 0) {
    return (
      <div className="card p-6">
        <div className="text-center py-8 text-gray-500">
          <FileVideo className="w-12 h-12 mx-auto mb-3 text-gray-300" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">没有任务</h3>
          <p>还没有创建任何批量缩略图生成任务</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 任务列表头部 */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">任务列表</h3>
          <p className="text-sm text-gray-600">共 {tasks.length} 个任务</p>
        </div>

        <div className="flex gap-2">
          <button
            onClick={onCleanup}
            className="px-3 py-2 text-sm bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition-colors flex items-center gap-2"
          >
            <Trash2 className="w-4 h-4" />
            清理已完成
          </button>
        </div>
      </div>

      {/* 任务统计 */}
      <div className="grid grid-cols-2 md:grid-cols-6 gap-3">
        {Object.entries(groupedTasks).map(([status, tasks]) => (
          <div key={status} className="text-center p-3 bg-gray-50 rounded-lg">
            <div className="text-lg font-semibold text-gray-900">
              {tasks.length}
            </div>
            <div className="text-xs text-gray-500">
              {TASK_STATUS_LABELS[status as TaskStatus]}
            </div>
          </div>
        ))}
      </div>

      {/* 任务分组列表 */}
      <div className="space-y-6">
        {renderTaskGroup(TaskStatus.Running, groupedTasks[TaskStatus.Running])}
        {renderTaskGroup(TaskStatus.Paused, groupedTasks[TaskStatus.Paused])}
        {renderTaskGroup(TaskStatus.Pending, groupedTasks[TaskStatus.Pending])}
        {renderTaskGroup(TaskStatus.Completed, groupedTasks[TaskStatus.Completed])}
        {renderTaskGroup(TaskStatus.Failed, groupedTasks[TaskStatus.Failed])}
        {renderTaskGroup(TaskStatus.Cancelled, groupedTasks[TaskStatus.Cancelled])}
      </div>
    </div>
  );
};
