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

interface BatchProgressProps {
  task: BatchThumbnailTask;
  onCancel: () => void;
  onPause: () => void;
  onResume: () => void;
}

/**
 * 批量处理进度组件
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
export const BatchProgress: React.FC<BatchProgressProps> = ({
  task,
  onCancel,
  onPause,
  onResume,
}) => {
  const { progress, status } = task;

  // 计算剩余时间显示
  const formatRemainingTime = (ms?: number): string => {
    if (!ms) return '未知';
    const seconds = Math.floor(ms / 1000);
    if (seconds < 60) return `${seconds}秒`;
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}分钟`;
    const hours = Math.floor(minutes / 60);
    return `${hours}小时${minutes % 60}分钟`;
  };

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

  return (
    <div className="card p-6 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">任务ID: {task.task_id}</p>
        </div>
        <div className="flex items-center gap-3">
          <span className={`px-3 py-1 rounded-full text-sm font-medium ${getStatusColor(status)}`}>
            {TASK_STATUS_LABELS[status]}
          </span>
          <div className="flex gap-2">
            {status === TaskStatus.Running && (
              <button
                onClick={onPause}
                className="p-2 text-orange-500 hover:text-orange-700 hover:bg-orange-50 rounded-lg transition-colors"
                title="暂停"
              >
                <Pause className="w-4 h-4" />
              </button>
            )}
            {status === TaskStatus.Paused && (
              <button
                onClick={onResume}
                className="p-2 text-green-500 hover:text-green-700 hover:bg-green-50 rounded-lg transition-colors"
                title="恢复"
              >
                <Play className="w-4 h-4" />
              </button>
            )}
            {(status === TaskStatus.Running || status === TaskStatus.Paused) && (
              <button
                onClick={onCancel}
                className="p-2 text-red-500 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors"
                title="取消"
              >
                <Square className="w-4 h-4" />
              </button>
            )}
          </div>
        </div>
      </div>

      {/* 进度条 */}
      <div className="space-y-3">
        <div className="flex items-center justify-between text-sm">
          <span className="text-gray-600">总体进度</span>
          <span className="font-medium">{progress.progress_percentage.toFixed(1)}%</span>
        </div>
        <div className="w-full bg-gray-200 rounded-full h-3">
          <div
            className="bg-blue-500 h-3 rounded-full transition-all duration-300"
            style={{ width: `${progress.progress_percentage}%` }}
          />
        </div>
        <div className="flex items-center justify-between text-xs text-gray-500">
          <span>
            {progress.processed_files + progress.failed_files} / {progress.total_files} 文件
          </span>
          {progress.estimated_remaining_ms && (
            <span className="flex items-center gap-1">
              <Clock className="w-3 h-3" />
              剩余 {formatRemainingTime(progress.estimated_remaining_ms)}
            </span>
          )}
        </div>
      </div>

      {/* 当前处理文件 */}
      {progress.current_file && status === TaskStatus.Running && (
        <div className="p-3 bg-blue-50 rounded-lg">
          <div className="flex items-center gap-2 text-sm">
            <FileVideo className="w-4 h-4 text-blue-500" />
            <span className="text-gray-600">正在处理:</span>
            <span className="font-medium text-blue-700 truncate">
              {progress.current_file.split(/[/\\]/).pop()}
            </span>
          </div>
        </div>
      )}

      {/* 统计信息 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="text-center p-3 bg-green-50 rounded-lg">
          <div className="flex items-center justify-center mb-1">
            <CheckCircle className="w-5 h-5 text-green-500" />
          </div>
          <div className="text-lg font-semibold text-green-700">
            {progress.processed_files}
          </div>
          <div className="text-xs text-green-600">已完成</div>
        </div>

        <div className="text-center p-3 bg-red-50 rounded-lg">
          <div className="flex items-center justify-center mb-1">
            <AlertCircle className="w-5 h-5 text-red-500" />
          </div>
          <div className="text-lg font-semibold text-red-700">
            {progress.failed_files}
          </div>
          <div className="text-xs text-red-600">失败</div>
        </div>

        <div className="text-center p-3 bg-gray-50 rounded-lg">
          <div className="flex items-center justify-center mb-1">
            <FileVideo className="w-5 h-5 text-gray-500" />
          </div>
          <div className="text-lg font-semibold text-gray-700">
            {progress.total_files}
          </div>
          <div className="text-xs text-gray-600">总文件</div>
        </div>

        <div className="text-center p-3 bg-purple-50 rounded-lg">
          <div className="flex items-center justify-center mb-1">
            <TrendingUp className="w-5 h-5 text-purple-500" />
          </div>
          <div className="text-lg font-semibold text-purple-700">
            {progress.processing_speed ? formatProcessingSpeed(progress.processing_speed) : '-'}
          </div>
          <div className="text-xs text-purple-600">处理速度</div>
        </div>
      </div>

      {/* 生成结果 */}
      {progress.results.length > 0 && (
        <div className="space-y-3">
          <h4 className="text-sm font-medium text-gray-700 flex items-center gap-2">
            <Image className="w-4 h-4" />
            生成结果 ({progress.results.length})
          </h4>
          <div className="max-h-48 overflow-y-auto space-y-2">
            {progress.results.slice(-10).map((result, index) => (
              <div
                key={index}
                className={`flex items-center gap-3 p-3 rounded-lg ${
                  result.success ? 'bg-green-50' : 'bg-red-50'
                }`}
              >
                <div className="flex-shrink-0">
                  {result.success ? (
                    <CheckCircle className="w-4 h-4 text-green-500" />
                  ) : (
                    <AlertCircle className="w-4 h-4 text-red-500" />
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium truncate">
                    {result.video_path.split(/[/\\]/).pop()}
                  </div>
                  <div className="text-xs text-gray-500">
                    {result.success ? (
                      <>
                        {result.output_paths.length} 个缩略图 • 
                        {result.processing_time_ms}ms • 
                        {formatFileSize(result.metadata.total_file_size)}
                      </>
                    ) : (
                      result.error_message
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 错误信息 */}
      {progress.errors.length > 0 && (
        <div className="space-y-3">
          <h4 className="text-sm font-medium text-red-700 flex items-center gap-2">
            <AlertCircle className="w-4 h-4" />
            错误信息 ({progress.errors.length})
          </h4>
          <div className="max-h-32 overflow-y-auto space-y-1">
            {progress.errors.slice(-5).map((error, index) => (
              <div key={index} className="text-xs text-red-600 p-2 bg-red-50 rounded">
                {error}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 任务时间信息 */}
      <div className="pt-4 border-t border-gray-200 text-xs text-gray-500 space-y-1">
        <div>创建时间: {new Date(task.created_at).toLocaleString()}</div>
        {task.started_at && (
          <div>开始时间: {new Date(task.started_at).toLocaleString()}</div>
        )}
        {task.completed_at && (
          <div>完成时间: {new Date(task.completed_at).toLocaleString()}</div>
        )}
      </div>
    </div>
  );
};
