/**
 * 执行监控器组件
 * 
 * 实时监控活跃的工作流执行状态，提供进度显示和控制功能
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect } from 'react';
import { 
  Activity, 
  Clock, 
  RefreshCw, 
  Square, 
  Eye, 
  AlertCircle,
  CheckCircle,
  XCircle,
  Zap,
  Server,
  Timer,
  Gauge
} from 'lucide-react';

// 执行状态枚举
type ExecutionStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';

// 执行记录接口
interface WorkflowExecutionRecord {
  id: number;
  workflow_template_id: number;
  workflow_name: string;
  workflow_version: string;
  execution_environment_id?: number;
  execution_environment_name?: string;
  input_data_json: any;
  output_data_json?: any;
  status: ExecutionStatus;
  progress: number;
  comfyui_prompt_id?: string;
  comfyui_workflow_name?: string;
  started_at?: string;
  completed_at?: string;
  duration_seconds?: number;
  error_message?: string;
  error_details_json?: any;
  user_id?: string;
  session_id?: string;
  metadata_json?: any;
  tags?: string[];
  created_at: string;
  updated_at: string;
}

// 组件属性接口
interface ExecutionMonitorProps {
  /** 活跃的执行记录 */
  activeExecutions: WorkflowExecutionRecord[];
  /** 取消执行回调 */
  onCancel: (executionId: number) => void;
  /** 查看日志回调 */
  onViewLogs: (executionId: number) => void;
  /** 查看详情回调 */
  onViewDetails?: (record: WorkflowExecutionRecord) => void;
  /** 刷新回调 */
  onRefresh?: () => void;
  /** 自动刷新间隔（毫秒） */
  refreshInterval?: number;
}

/**
 * 执行监控器组件
 */
export const ExecutionMonitor: React.FC<ExecutionMonitorProps> = ({
  activeExecutions,
  onCancel,
  onViewLogs,
  onViewDetails,
  onRefresh,
  refreshInterval = 2000
}) => {
  const [lastUpdateTime, setLastUpdateTime] = useState<Date>(new Date());

  // 自动刷新
  useEffect(() => {
    if (!onRefresh || refreshInterval <= 0) return;

    const interval = setInterval(() => {
      onRefresh();
      setLastUpdateTime(new Date());
    }, refreshInterval);

    return () => clearInterval(interval);
  }, [onRefresh, refreshInterval]);

  // 获取状态图标
  const getStatusIcon = (status: ExecutionStatus) => {
    switch (status) {
      case 'pending':
        return <Clock className="w-4 h-4 text-yellow-500" />;
      case 'running':
        return <RefreshCw className="w-4 h-4 text-blue-500 animate-spin" />;
      case 'completed':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'failed':
        return <XCircle className="w-4 h-4 text-red-500" />;
      case 'cancelled':
        return <AlertCircle className="w-4 h-4 text-gray-500" />;
      default:
        return <Clock className="w-4 h-4 text-gray-400" />;
    }
  };

  // 获取状态文本
  const getStatusText = (status: ExecutionStatus) => {
    const statusMap = {
      pending: '等待中',
      running: '执行中',
      completed: '已完成',
      failed: '失败',
      cancelled: '已取消'
    };
    return statusMap[status] || '未知';
  };

  // 计算执行时间
  const getExecutionTime = (startedAt?: string) => {
    if (!startedAt) return '-';
    
    const start = new Date(startedAt);
    const now = new Date();
    const diffMs = now.getTime() - start.getTime();
    const diffSeconds = Math.floor(diffMs / 1000);
    
    if (diffSeconds < 60) {
      return `${diffSeconds}秒`;
    } else if (diffSeconds < 3600) {
      const minutes = Math.floor(diffSeconds / 60);
      const seconds = diffSeconds % 60;
      return `${minutes}分${seconds}秒`;
    } else {
      const hours = Math.floor(diffSeconds / 3600);
      const minutes = Math.floor((diffSeconds % 3600) / 60);
      return `${hours}小时${minutes}分钟`;
    }
  };

  // 估算剩余时间
  const getEstimatedTimeRemaining = (progress: number, startedAt?: string) => {
    if (!startedAt || progress <= 0) return '-';
    
    const start = new Date(startedAt);
    const now = new Date();
    const elapsedMs = now.getTime() - start.getTime();
    
    if (progress >= 100) return '即将完成';
    
    const estimatedTotalMs = (elapsedMs / progress) * 100;
    const remainingMs = estimatedTotalMs - elapsedMs;
    const remainingSeconds = Math.floor(remainingMs / 1000);
    
    if (remainingSeconds < 60) {
      return `约${remainingSeconds}秒`;
    } else if (remainingSeconds < 3600) {
      const minutes = Math.floor(remainingSeconds / 60);
      return `约${minutes}分钟`;
    } else {
      const hours = Math.floor(remainingSeconds / 3600);
      const minutes = Math.floor((remainingSeconds % 3600) / 60);
      return `约${hours}小时${minutes}分钟`;
    }
  };

  // 格式化时间
  const formatTime = (date: Date) => {
    return date.toLocaleTimeString('zh-CN');
  };

  // 统计信息
  const stats = {
    total: activeExecutions.length,
    pending: activeExecutions.filter(e => e.status === 'pending').length,
    running: activeExecutions.filter(e => e.status === 'running').length,
    completed: activeExecutions.filter(e => e.status === 'completed').length,
    failed: activeExecutions.filter(e => e.status === 'failed').length
  };

  return (
    <div className="space-y-6">
      {/* 监控头部 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-3">
          <Activity className="w-6 h-6 text-blue-600" />
          <div>
            <h2 className="text-lg font-medium text-gray-900">
              实时执行监控
            </h2>
            <p className="text-sm text-gray-500">
              最后更新: {formatTime(lastUpdateTime)}
            </p>
          </div>
        </div>

        <div className="flex items-center space-x-4">
          {/* 统计信息 */}
          <div className="flex items-center space-x-4 text-sm">
            <div className="flex items-center space-x-1">
              <div className="w-2 h-2 bg-yellow-500 rounded-full"></div>
              <span className="text-gray-600">等待: {stats.pending}</span>
            </div>
            <div className="flex items-center space-x-1">
              <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
              <span className="text-gray-600">执行: {stats.running}</span>
            </div>
            <div className="flex items-center space-x-1">
              <div className="w-2 h-2 bg-green-500 rounded-full"></div>
              <span className="text-gray-600">完成: {stats.completed}</span>
            </div>
            <div className="flex items-center space-x-1">
              <div className="w-2 h-2 bg-red-500 rounded-full"></div>
              <span className="text-gray-600">失败: {stats.failed}</span>
            </div>
          </div>

          {onRefresh && (
            <button
              onClick={onRefresh}
              className="px-3 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors flex items-center space-x-1"
            >
              <RefreshCw className="w-4 h-4" />
              <span>刷新</span>
            </button>
          )}
        </div>
      </div>

      {/* 执行列表 */}
      {activeExecutions.length === 0 ? (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-8 text-center">
          <Activity className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            暂无活跃执行
          </h3>
          <p className="text-gray-600">
            当前没有正在执行或等待执行的工作流
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {activeExecutions.map((execution) => (
            <div
              key={execution.id}
              className="bg-white rounded-lg shadow-sm border border-gray-200 p-4"
            >
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  {/* 执行基本信息 */}
                  <div className="flex items-center space-x-3 mb-3">
                    {getStatusIcon(execution.status)}
                    <div className="flex-1">
                      <div className="flex items-center space-x-2">
                        <h3 className="text-sm font-medium text-gray-900">
                          {execution.workflow_name}
                        </h3>
                        <span className="text-xs text-gray-500">
                          v{execution.workflow_version}
                        </span>
                        <span className={`px-2 py-1 text-xs rounded-full ${
                          execution.status === 'running' 
                            ? 'bg-blue-100 text-blue-800'
                            : execution.status === 'pending'
                            ? 'bg-yellow-100 text-yellow-800'
                            : execution.status === 'completed'
                            ? 'bg-green-100 text-green-800'
                            : 'bg-red-100 text-red-800'
                        }`}>
                          {getStatusText(execution.status)}
                        </span>
                      </div>
                      <div className="flex items-center space-x-4 mt-1 text-xs text-gray-500">
                        <div className="flex items-center space-x-1">
                          <Timer className="w-3 h-3" />
                          <span>ID: {execution.id}</span>
                        </div>
                        {execution.execution_environment_name && (
                          <div className="flex items-center space-x-1">
                            <Server className="w-3 h-3" />
                            <span>{execution.execution_environment_name}</span>
                          </div>
                        )}
                        {execution.comfyui_prompt_id && (
                          <div className="flex items-center space-x-1">
                            <Zap className="w-3 h-3" />
                            <span>ComfyUI: {execution.comfyui_prompt_id}</span>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* 进度条 */}
                  {execution.status === 'running' && (
                    <div className="mb-3">
                      <div className="flex items-center justify-between text-xs text-gray-600 mb-1">
                        <span>执行进度</span>
                        <span>{execution.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: `${execution.progress}%` }}
                        />
                      </div>
                    </div>
                  )}

                  {/* 时间信息 */}
                  <div className="grid grid-cols-2 gap-4 text-xs text-gray-600">
                    <div className="flex items-center space-x-1">
                      <Clock className="w-3 h-3" />
                      <span>已执行: {getExecutionTime(execution.started_at)}</span>
                    </div>
                    {execution.status === 'running' && (
                      <div className="flex items-center space-x-1">
                        <Gauge className="w-3 h-3" />
                        <span>预计剩余: {getEstimatedTimeRemaining(execution.progress, execution.started_at)}</span>
                      </div>
                    )}
                  </div>

                  {/* 错误信息 */}
                  {execution.error_message && (
                    <div className="mt-2 p-2 bg-red-50 border border-red-200 rounded text-xs text-red-700">
                      {execution.error_message}
                    </div>
                  )}
                </div>

                {/* 操作按钮 */}
                <div className="flex items-center space-x-2 ml-4">
                  <button
                    onClick={() => onViewLogs(execution.id)}
                    className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
                    title="查看日志"
                  >
                    <Eye className="w-4 h-4" />
                  </button>

                  {onViewDetails && (
                    <button
                      onClick={() => onViewDetails(execution)}
                      className="p-1 text-gray-400 hover:text-green-600 transition-colors"
                      title="查看详情"
                    >
                      <Activity className="w-4 h-4" />
                    </button>
                  )}

                  {(execution.status === 'pending' || execution.status === 'running') && (
                    <button
                      onClick={() => onCancel(execution.id)}
                      className="p-1 text-gray-400 hover:text-red-600 transition-colors"
                      title="取消执行"
                    >
                      <Square className="w-4 h-4" />
                    </button>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};
