/**
 * 队列状态监控组件
 * 实时显示 ComfyUI 队列状态和统计信息
 */

import React, { useState, useEffect } from 'react';
import {
  QueueListIcon,
  PlayIcon,
  ClockIcon,
  CheckCircleIcon,
  XCircleIcon,
  ChartBarIcon,
  ArrowPathIcon,
  PauseIcon,
  StopIcon,
} from '@heroicons/react/24/outline';
import { useComfyUIV2Store } from '../../store/comfyuiV2Store';

interface QueueStatusMonitorProps {
  className?: string;
  showChart?: boolean;
}

export const QueueStatusMonitor: React.FC<QueueStatusMonitorProps> = ({
  className = '',
  showChart = false,
}) => {
  const {
    queueStatus,
    realtimeEvents,
    refreshQueueStatus,
    isConnected,
  } = useComfyUIV2Store();

  const [autoRefresh, setAutoRefresh] = useState(true);
  const [refreshInterval, setRefreshInterval] = useState<NodeJS.Timeout>();
  const [queueHistory, setQueueHistory] = useState<Array<{
    timestamp: number;
    running: number;
    pending: number;
  }>>([]);

  // 自动刷新队列状态
  useEffect(() => {
    if (autoRefresh && isConnected) {
      const interval = setInterval(() => {
        refreshQueueStatus();
      }, 2000); // 每2秒刷新一次
      
      setRefreshInterval(interval);
      return () => clearInterval(interval);
    } else if (refreshInterval) {
      clearInterval(refreshInterval);
    }
  }, [autoRefresh, isConnected, refreshQueueStatus]);

  // 记录队列历史数据
  useEffect(() => {
    if (queueStatus) {
      setQueueHistory(prev => {
        const newEntry = {
          timestamp: Date.now(),
          running: queueStatus.running_count,
          pending: queueStatus.pending_count,
        };
        
        const updated = [...prev, newEntry];
        // 只保留最近30个数据点
        return updated.slice(-30);
      });
    }
  }, [queueStatus]);

  // 监听队列相关的实时事件
  const queueEvents = realtimeEvents.filter(event => 
    event.event_type === 'queue_updated' ||
    event.event_type === 'execution_started' ||
    event.event_type === 'execution_completed' ||
    event.event_type === 'execution_failed'
  ).slice(0, 5); // 只显示最近5个事件

  const getQueueStatusColor = () => {
    if (!queueStatus) return 'text-gray-500';
    
    if (queueStatus.running_count > 0) return 'text-blue-600';
    if (queueStatus.pending_count > 0) return 'text-yellow-600';
    return 'text-green-600';
  };

  const getQueueStatusText = () => {
    if (!queueStatus) return '未知';
    
    if (queueStatus.running_count > 0) return '执行中';
    if (queueStatus.pending_count > 0) return '等待中';
    return '空闲';
  };

  const getTotalTasks = () => {
    if (!queueStatus) return 0;
    return queueStatus.running_count + queueStatus.pending_count;
  };

  const getEventIcon = (eventType: string) => {
    switch (eventType) {
      case 'queue_updated':
        return <QueueListIcon className="w-4 h-4 text-purple-600" />;
      case 'execution_started':
        return <PlayIcon className="w-4 h-4 text-blue-600" />;
      case 'execution_completed':
        return <CheckCircleIcon className="w-4 h-4 text-green-600" />;
      case 'execution_failed':
        return <XCircleIcon className="w-4 h-4 text-red-600" />;
      default:
        return <ClockIcon className="w-4 h-4 text-gray-400" />;
    }
  };

  const getEventLabel = (eventType: string) => {
    const labels = {
      queue_updated: '队列更新',
      execution_started: '开始执行',
      execution_completed: '执行完成',
      execution_failed: '执行失败',
    };
    return labels[eventType as keyof typeof labels] || eventType;
  };

  if (!isConnected) {
    return (
      <div className={`bg-gray-50 rounded-lg border border-gray-200 p-4 ${className}`}>
        <div className="flex items-center space-x-2 text-gray-500">
          <QueueListIcon className="w-5 h-5" />
          <span className="text-sm">请先连接到 ComfyUI 服务</span>
        </div>
      </div>
    );
  }

  return (
    <div className={`bg-white rounded-lg shadow-sm border border-gray-200 ${className}`}>
      {/* 头部 */}
      <div className="px-4 py-3 border-b border-gray-200">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <QueueListIcon className="w-6 h-6 text-blue-600" />
            <div>
              <h3 className="text-lg font-semibold text-gray-900">队列状态</h3>
              <div className="flex items-center space-x-2 mt-1">
                <div className={`w-3 h-3 rounded-full ${
                  queueStatus?.running_count ? 'bg-blue-500' : 
                  queueStatus?.pending_count ? 'bg-yellow-500' : 'bg-green-500'
                }`} />
                <span className={`text-sm font-medium ${getQueueStatusColor()}`}>
                  {getQueueStatusText()}
                </span>
              </div>
            </div>
          </div>
          
          <div className="flex items-center space-x-2">
            <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-4 h-4" />
              ) : (
                <PlayIcon className="w-4 h-4" />
              )}
            </button>
            
            <button
              onClick={refreshQueueStatus}
              className="p-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
              title="手动刷新"
            >
              <ArrowPathIcon className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* 队列统计 */}
      <div className="px-4 py-4">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-600">
              {queueStatus?.running_count || 0}
            </div>
            <div className="text-sm text-gray-500">执行中</div>
          </div>
          
          <div className="text-center">
            <div className="text-2xl font-bold text-yellow-600">
              {queueStatus?.pending_count || 0}
            </div>
            <div className="text-sm text-gray-500">等待中</div>
          </div>
          
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-900">
              {getTotalTasks()}
            </div>
            <div className="text-sm text-gray-500">总任务</div>
          </div>
          
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600">
              {queueStatus?.history_count || 0}
            </div>
            <div className="text-sm text-gray-500">历史记录</div>
          </div>
        </div>
      </div>

      {/* 队列进度条 */}
      {getTotalTasks() > 0 && (
        <div className="px-4 pb-4">
          <div className="bg-gray-200 rounded-full h-3 overflow-hidden">
            <div className="h-full flex">
              {queueStatus?.running_count && queueStatus.running_count > 0 && (
                <div
                  className="bg-blue-500 h-full"
                  style={{
                    width: `${(queueStatus.running_count / getTotalTasks()) * 100}%`
                  }}
                />
              )}
              {queueStatus?.pending_count && queueStatus.pending_count > 0 && (
                <div
                  className="bg-yellow-500 h-full"
                  style={{
                    width: `${(queueStatus.pending_count / getTotalTasks()) * 100}%`
                  }}
                />
              )}
            </div>
          </div>
          <div className="flex justify-between text-xs text-gray-500 mt-1">
            <span>执行中: {queueStatus?.running_count || 0}</span>
            <span>等待中: {queueStatus?.pending_count || 0}</span>
          </div>
        </div>
      )}

      {/* 简单图表 */}
      {showChart && queueHistory.length > 1 && (
        <div className="px-4 py-4 border-t border-gray-200">
          <div className="flex items-center space-x-2 mb-3">
            <ChartBarIcon className="w-5 h-5 text-gray-600" />
            <span className="text-sm font-medium text-gray-700">队列趋势</span>
          </div>
          
          <div className="h-20 flex items-end space-x-1">
            {queueHistory.slice(-20).map((entry, index) => {
              const maxValue = Math.max(...queueHistory.map(h => h.running + h.pending));
              const totalHeight = maxValue > 0 ? ((entry.running + entry.pending) / maxValue) * 100 : 0;
              const runningHeight = maxValue > 0 ? (entry.running / maxValue) * 100 : 0;
              
              return (
                <div
                  key={entry.timestamp}
                  className="flex-1 flex flex-col justify-end"
                  style={{ height: '100%' }}
                >
                  <div
                    className="bg-yellow-400 rounded-t"
                    style={{ height: `${totalHeight - runningHeight}%` }}
                  />
                  <div
                    className="bg-blue-500 rounded-b"
                    style={{ height: `${runningHeight}%` }}
                  />
                </div>
              );
            })}
          </div>
          
          <div className="flex items-center justify-center space-x-4 mt-2 text-xs text-gray-500">
            <div className="flex items-center space-x-1">
              <div className="w-3 h-3 bg-blue-500 rounded" />
              <span>执行中</span>
            </div>
            <div className="flex items-center space-x-1">
              <div className="w-3 h-3 bg-yellow-400 rounded" />
              <span>等待中</span>
            </div>
          </div>
        </div>
      )}

      {/* 最近事件 */}
      {queueEvents.length > 0 && (
        <div className="border-t border-gray-200">
          <div className="px-4 py-3">
            <div className="text-sm font-medium text-gray-700 mb-2">最近事件</div>
            <div className="space-y-2">
              {queueEvents.map((event, index) => (
                <div
                  key={`${event.timestamp}-${event.event_type}-${index}`}
                  className="flex items-center space-x-3 text-sm"
                >
                  <div className="flex-shrink-0">
                    {getEventIcon(event.event_type)}
                  </div>
                  
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center space-x-2">
                      <span className="font-medium text-gray-900">
                        {getEventLabel(event.event_type)}
                      </span>
                      <span className="text-xs text-gray-500">
                        {new Date(event.timestamp).toLocaleTimeString()}
                      </span>
                    </div>
                    
                    {event.event_type === 'queue_updated' && event.data && (
                      <div className="text-gray-600 text-xs">
                        运行: {event.data.running_count}, 等待: {event.data.pending_count}
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* 状态指示器 */}
      <div className="px-4 py-3 border-t border-gray-200 bg-gray-50">
        <div className="flex items-center justify-between text-sm">
          <div className="flex items-center space-x-2 text-gray-600">
            {autoRefresh ? (
              <>
                <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
                <span>自动刷新中</span>
              </>
            ) : (
              <>
                <div className="w-2 h-2 bg-gray-400 rounded-full" />
                <span>手动刷新</span>
              </>
            )}
          </div>
          
          <div className="text-gray-500">
            {queueStatus && (
              <span>
                最后更新: {new Date().toLocaleTimeString()}
              </span>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
