/**
 * 执行监控组件
 * 实时显示工作流和模板的执行状态和进度
 */

import React, { useState, useEffect } from 'react';
import {
  PlayIcon,
  PauseIcon,
  StopIcon,
  CheckCircleIcon,
  XCircleIcon,
  ClockIcon,
  ExclamationTriangleIcon,
  EyeIcon,
  ArrowPathIcon,
} from '@heroicons/react/24/outline';
import { useComfyUIV2Store, useFilteredExecutions } from '../../store/comfyuiV2Store';
import type { ExecutionV2 } from '../../services/comfyuiV2Service';

interface ExecutionMonitorProps {
  className?: string;
  showCompleted?: boolean;
  maxItems?: number;
}

export const ExecutionMonitor: React.FC<ExecutionMonitorProps> = ({
  className = '',
  showCompleted: initialShowCompleted = true,
  maxItems = 10,
}) => {
  const {
    executions,
    executionsLoading,
    executionsError,
    currentExecution,
    executionFilters,
    loadExecutions,
    cancelExecution,
    setCurrentExecution,
    setExecutionFilters,
  } = useComfyUIV2Store();

  const filteredExecutions = useFilteredExecutions();
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [showCompleted, setShowCompleted] = useState(initialShowCompleted);
  const [refreshInterval, setRefreshInterval] = useState<NodeJS.Timeout>();

  // 自动刷新执行列表
  useEffect(() => {
    if (autoRefresh) {
      const interval = setInterval(() => {
        loadExecutions();
      }, 3000); // 每3秒刷新一次
      
      setRefreshInterval(interval);
      return () => clearInterval(interval);
    } else if (refreshInterval) {
      clearInterval(refreshInterval);
    }
  }, [autoRefresh, loadExecutions]);

  // 初始加载
  useEffect(() => {
    loadExecutions();
  }, [loadExecutions]);

  const getStatusIcon = (status: ExecutionV2['status']) => {
    switch (status) {
      case 'pending':
        return <ClockIcon className="w-5 h-5 text-yellow-600" />;
      case 'running':
        return <PlayIcon className="w-5 h-5 text-blue-600" />;
      case 'completed':
        return <CheckCircleIcon className="w-5 h-5 text-green-600" />;
      case 'failed':
        return <XCircleIcon className="w-5 h-5 text-red-600" />;
      case 'cancelled':
        return <StopIcon className="w-5 h-5 text-gray-600" />;
      default:
        return <ClockIcon className="w-5 h-5 text-gray-400" />;
    }
  };

  const getStatusLabel = (status: ExecutionV2['status']) => {
    const labels = {
      pending: '等待中',
      running: '执行中',
      completed: '已完成',
      failed: '失败',
      cancelled: '已取消',
    };
    return labels[status] || status;
  };

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

  const handleCancelExecution = async (execution: ExecutionV2) => {
    if (window.confirm(`确定要取消执行 "${execution.id}" 吗？`)) {
      try {
        await cancelExecution(execution.id);
      } catch (error) {
        console.error('取消执行失败:', error);
      }
    }
  };

  const getRunningExecutions = () => {
    return filteredExecutions.filter(e => e.status === 'running' || e.status === 'pending');
  };

  const getRecentExecutions = () => {
    const filtered = showCompleted 
      ? filteredExecutions 
      : filteredExecutions.filter(e => e.status !== 'completed');
    
    return filtered
      .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
      .slice(0, maxItems);
  };

  if (executionsError) {
    return (
      <div className={`bg-white rounded-lg shadow-sm border border-gray-200 p-6 ${className}`}>
        <div className="text-center">
          <ExclamationTriangleIcon className="w-8 h-8 text-red-600 mx-auto mb-2" />
          <div className="text-red-600 mb-2">加载执行记录失败</div>
          <div className="text-sm text-gray-500 mb-4">{executionsError}</div>
          <button
            onClick={loadExecutions}
            className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  const runningExecutions = getRunningExecutions();
  const recentExecutions = getRecentExecutions();

  return (
    <div className={`bg-white rounded-lg shadow-sm border border-gray-200 ${className}`}>
      {/* 头部 */}
      <div className="px-6 py-4 border-b border-gray-200">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-semibold text-gray-900">执行监控</h3>
            <p className="text-sm text-gray-500 mt-1">
              运行中: {runningExecutions.length} | 总计: {filteredExecutions.length}
            </p>
          </div>
          
          <div className="flex items-center space-x-3">
            <button
              onClick={() => setAutoRefresh(!autoRefresh)}
              className={`p-2 rounded-lg border ${
                autoRefresh 
                  ? 'bg-green-50 border-green-200 text-green-600' 
                  : 'border-gray-300 text-gray-600 hover:bg-gray-50'
              }`}
              title={autoRefresh ? '停止自动刷新' : '启动自动刷新'}
            >
              {autoRefresh ? (
                <PauseIcon className="w-5 h-5" />
              ) : (
                <PlayIcon className="w-5 h-5" />
              )}
            </button>
            
            <button
              onClick={loadExecutions}
              disabled={executionsLoading}
              className="p-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50"
              title="手动刷新"
            >
              <ArrowPathIcon className={`w-5 h-5 ${executionsLoading ? 'animate-spin' : ''}`} />
            </button>
          </div>
        </div>
      </div>

      {/* 筛选器 */}
      <div className="px-6 py-3 border-b border-gray-200 bg-gray-50">
        <div className="flex items-center space-x-4">
          <div className="flex items-center space-x-2">
            <label className="text-sm font-medium text-gray-700">状态:</label>
            <select
              value={executionFilters.status || ''}
              onChange={(e) => setExecutionFilters({ status: e.target.value || undefined })}
              className="text-sm border border-gray-300 rounded px-2 py-1 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="">全部</option>
              <option value="pending">等待中</option>
              <option value="running">执行中</option>
              <option value="completed">已完成</option>
              <option value="failed">失败</option>
              <option value="cancelled">已取消</option>
            </select>
          </div>
          
          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              id="showCompleted"
              checked={showCompleted}
              onChange={(e) => setShowCompleted(e.target.checked)}
              className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
            />
            <label htmlFor="showCompleted" className="text-sm text-gray-700">
              显示已完成
            </label>
          </div>
        </div>
      </div>

      {/* 执行列表 */}
      <div className="divide-y divide-gray-200">
        {executionsLoading && recentExecutions.length === 0 ? (
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <span className="ml-3 text-gray-600">加载中...</span>
          </div>
        ) : recentExecutions.length === 0 ? (
          <div className="text-center py-12">
            <ClockIcon className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <div className="text-gray-500">暂无执行记录</div>
          </div>
        ) : (
          recentExecutions.map(execution => (
            <ExecutionItem
              key={execution.id}
              execution={execution}
              isSelected={currentExecution?.id === execution.id}
              onSelect={() => setCurrentExecution(execution)}
              onCancel={() => handleCancelExecution(execution)}
            />
          ))
        )}
      </div>

      {/* 底部统计 */}
      {recentExecutions.length > 0 && (
        <div className="px-6 py-3 border-t border-gray-200 bg-gray-50">
          <div className="flex items-center justify-between text-sm text-gray-600">
            <div>
              显示 {recentExecutions.length} / {filteredExecutions.length} 条记录
            </div>
            <div className="flex items-center space-x-4">
              {runningExecutions.length > 0 && (
                <div className="flex items-center space-x-1">
                  <div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse" />
                  <span>{runningExecutions.length} 个正在执行</span>
                </div>
              )}
              {autoRefresh && (
                <div className="text-xs text-gray-500">
                  自动刷新中...
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 执行项组件
interface ExecutionItemProps {
  execution: ExecutionV2;
  isSelected: boolean;
  onSelect: () => void;
  onCancel: () => void;
}

const ExecutionItem: React.FC<ExecutionItemProps> = ({
  execution,
  isSelected,
  onSelect,
  onCancel,
}) => {
  const getStatusIcon = (status: ExecutionV2['status']) => {
    switch (status) {
      case 'pending':
        return <ClockIcon className="w-5 h-5 text-yellow-600" />;
      case 'running':
        return <PlayIcon className="w-5 h-5 text-blue-600" />;
      case 'completed':
        return <CheckCircleIcon className="w-5 h-5 text-green-600" />;
      case 'failed':
        return <XCircleIcon className="w-5 h-5 text-red-600" />;
      case 'cancelled':
        return <StopIcon className="w-5 h-5 text-gray-600" />;
      default:
        return <ClockIcon className="w-5 h-5 text-gray-400" />;
    }
  };

  const getStatusLabel = (status: ExecutionV2['status']) => {
    const labels = {
      pending: '等待中',
      running: '执行中',
      completed: '已完成',
      failed: '失败',
      cancelled: '已取消',
    };
    return labels[status] || status;
  };

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

  return (
    <div className={`p-4 hover:bg-gray-50 cursor-pointer ${
      isSelected ? 'bg-blue-50 border-l-4 border-l-blue-500' : ''
    }`} onClick={onSelect}>
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4 flex-1">
          <div className="flex-shrink-0">
            {getStatusIcon(execution.status)}
          </div>
          
          <div className="flex-1 min-w-0">
            <div className="flex items-center space-x-3">
              <div className="font-medium text-gray-900 truncate">
                {execution.workflow_id ? '工作流执行' : '模板执行'}
              </div>
              
              <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium border ${
                getStatusColor(execution.status)
              }`}>
                {getStatusLabel(execution.status)}
              </span>
            </div>
            
            <div className="flex items-center space-x-4 mt-1 text-sm text-gray-500">
              <div className="font-mono">
                {execution.id.slice(0, 8)}...
              </div>
              
              <div>
                {new Date(execution.created_at).toLocaleString()}
              </div>
              
              {execution.execution_time && (
                <div>
                  耗时: {execution.execution_time}ms
                </div>
              )}
            </div>
            
            {/* 进度条 */}
            {execution.status === 'running' && execution.progress !== undefined && (
              <div className="mt-2">
                <div className="flex items-center justify-between text-xs text-gray-600 mb-1">
                  <span>执行进度</span>
                  <span>{execution.progress.toFixed(1)}%</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>
            )}
            
            {/* 错误信息 */}
            {execution.status === 'failed' && execution.error_message && (
              <div className="mt-2 p-2 bg-red-50 border border-red-200 rounded text-sm text-red-700">
                {execution.error_message}
              </div>
            )}
          </div>
        </div>
        
        <div className="flex items-center space-x-2 ml-4">
          <button
            onClick={(e) => {
              e.stopPropagation();
              onSelect();
            }}
            className="p-1 text-gray-400 hover:text-gray-600"
            title="查看详情"
          >
            <EyeIcon className="w-4 h-4" />
          </button>
          
          {(execution.status === 'running' || execution.status === 'pending') && (
            <button
              onClick={(e) => {
                e.stopPropagation();
                onCancel();
              }}
              className="p-1 text-red-600 hover:text-red-700"
              title="取消执行"
            >
              <StopIcon className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>
    </div>
  );
};
