/**
 * 实时事件监听器组件
 * 负责监听和处理 ComfyUI 实时事件，同步状态到前端
 */

import React, { useEffect, useRef, useState } from 'react';
import { 
  WifiIcon, 
  ExclamationTriangleIcon,
  CheckCircleIcon,
  XCircleIcon,
  ClockIcon,
  PlayIcon,
  PauseIcon,
} from '@heroicons/react/24/outline';
import { useComfyUIV2Store } from '../../store/comfyuiV2Store';
import type { RealtimeEvent } from '../../services/comfyuiV2Service';

interface RealtimeEventListenerProps {
  className?: string;
  showEventLog?: boolean;
  maxEvents?: number;
}

export const RealtimeEventListener: React.FC<RealtimeEventListenerProps> = ({
  className = '',
  showEventLog = false,
  maxEvents = 100,
}) => {
  const {
    isConnected,
    realtimeConnected,
    realtimeEvents,
    realtimeSubscriptionId,
    startRealtimeMonitor,
    stopRealtimeMonitor,
    subscribeRealtimeEvents,
    unsubscribeRealtimeEvents,
    clearRealtimeEvents,
  } = useComfyUIV2Store();

  const [isStarting, setIsStarting] = useState(false);
  const [isStopping, setIsStopping] = useState(false);
  const [eventStats, setEventStats] = useState({
    total: 0,
    lastMinute: 0,
    byType: {} as Record<string, number>,
  });

  const eventLogRef = useRef<HTMLDivElement>(null);
  const statsIntervalRef = useRef<NodeJS.Timeout>();

  // 自动滚动到最新事件
  useEffect(() => {
    if (eventLogRef.current && showEventLog) {
      eventLogRef.current.scrollTop = eventLogRef.current.scrollHeight;
    }
  }, [realtimeEvents, showEventLog]);

  // 计算事件统计
  useEffect(() => {
    const updateStats = () => {
      const now = Date.now();
      const oneMinuteAgo = now - 60000;
      
      const recentEvents = realtimeEvents.filter(event => 
        new Date(event.timestamp).getTime() > oneMinuteAgo
      );

      const byType: Record<string, number> = {};
      realtimeEvents.forEach(event => {
        byType[event.event_type] = (byType[event.event_type] || 0) + 1;
      });

      setEventStats({
        total: realtimeEvents.length,
        lastMinute: recentEvents.length,
        byType,
      });
    };

    updateStats();
    statsIntervalRef.current = setInterval(updateStats, 5000);

    return () => {
      if (statsIntervalRef.current) {
        clearInterval(statsIntervalRef.current);
      }
    };
  }, [realtimeEvents]);

  // 自动启动实时监控
  useEffect(() => {
    if (isConnected && !realtimeConnected && !isStarting) {
      handleStartRealtimeMonitor();
    }
  }, [isConnected]);

  const handleStartRealtimeMonitor = async () => {
    if (!isConnected) return;
    
    setIsStarting(true);
    try {
      await startRealtimeMonitor();
      await subscribeRealtimeEvents();
    } catch (error) {
      console.error('启动实时监控失败:', error);
    } finally {
      setIsStarting(false);
    }
  };

  const handleStopRealtimeMonitor = async () => {
    setIsStopping(true);
    try {
      await stopRealtimeMonitor();
    } catch (error) {
      console.error('停止实时监控失败:', error);
    } finally {
      setIsStopping(false);
    }
  };

  const getEventIcon = (eventType: string) => {
    switch (eventType) {
      case 'connection_changed':
        return <WifiIcon className="w-4 h-4" />;
      case 'execution_started':
        return <PlayIcon className="w-4 h-4 text-blue-600" />;
      case 'execution_progress':
        return <ClockIcon className="w-4 h-4 text-yellow-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" />;
      case 'node_executing':
        return <PlayIcon className="w-4 h-4 text-blue-500" />;
      case 'queue_updated':
        return <ClockIcon className="w-4 h-4 text-purple-600" />;
      case 'system_status_updated':
        return <ExclamationTriangleIcon className="w-4 h-4 text-orange-600" />;
      default:
        return <div className="w-4 h-4 bg-gray-400 rounded-full" />;
    }
  };

  const getEventTypeLabel = (eventType: string) => {
    const labels: Record<string, string> = {
      connection_changed: '连接状态',
      execution_started: '执行开始',
      execution_progress: '执行进度',
      execution_completed: '执行完成',
      execution_failed: '执行失败',
      node_executing: '节点执行',
      queue_updated: '队列更新',
      system_status_updated: '系统状态',
    };
    return labels[eventType] || eventType;
  };

  const formatEventData = (event: RealtimeEvent) => {
    switch (event.event_type) {
      case 'execution_progress':
        return `进度: ${event.data.percentage?.toFixed(1)}%`;
      case 'execution_completed':
        return `耗时: ${event.data.execution_time}ms`;
      case 'execution_failed':
        return `错误: ${event.data.error}`;
      case 'queue_updated':
        return `运行: ${event.data.running_count}, 等待: ${event.data.pending_count}`;
      case 'connection_changed':
        return event.data.connected ? '已连接' : '已断开';
      default:
        return '';
    }
  };

  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">
          <WifiIcon 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">
            <div className="flex items-center space-x-2">
              <div className={`w-3 h-3 rounded-full ${
                realtimeConnected ? 'bg-green-500' : 'bg-gray-400'
              }`} />
              <span className="text-sm font-medium text-gray-900">
                实时监控
              </span>
            </div>
            
            {realtimeConnected && (
              <div className="text-xs text-gray-500">
                {eventStats.lastMinute} 事件/分钟
              </div>
            )}
          </div>
          
          <div className="flex items-center space-x-2">
            {showEventLog && (
              <button
                onClick={clearRealtimeEvents}
                className="px-2 py-1 text-xs text-gray-600 hover:text-gray-800"
                disabled={realtimeEvents.length === 0}
              >
                清空日志
              </button>
            )}
            
            {realtimeConnected ? (
              <button
                onClick={handleStopRealtimeMonitor}
                disabled={isStopping}
                className="px-3 py-1 text-xs font-medium text-red-700 bg-red-50 border border-red-200 rounded hover:bg-red-100 disabled:opacity-50"
              >
                {isStopping ? '停止中...' : '停止监控'}
              </button>
            ) : (
              <button
                onClick={handleStartRealtimeMonitor}
                disabled={isStarting}
                className="px-3 py-1 text-xs font-medium text-green-700 bg-green-50 border border-green-200 rounded hover:bg-green-100 disabled:opacity-50"
              >
                {isStarting ? '启动中...' : '启动监控'}
              </button>
            )}
          </div>
        </div>
      </div>

      {/* 统计信息 */}
      {realtimeConnected && (
        <div className="px-4 py-3 bg-gray-50 border-b border-gray-200">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
            <div>
              <div className="text-lg font-semibold text-gray-900">{eventStats.total}</div>
              <div className="text-xs text-gray-500">总事件数</div>
            </div>
            <div>
              <div className="text-lg font-semibold text-gray-900">{eventStats.lastMinute}</div>
              <div className="text-xs text-gray-500">最近一分钟</div>
            </div>
            <div>
              <div className="text-lg font-semibold text-gray-900">
                {Object.keys(eventStats.byType).length}
              </div>
              <div className="text-xs text-gray-500">事件类型</div>
            </div>
            <div>
              <div className="text-lg font-semibold text-gray-900">
                {realtimeSubscriptionId ? '已订阅' : '未订阅'}
              </div>
              <div className="text-xs text-gray-500">订阅状态</div>
            </div>
          </div>
        </div>
      )}

      {/* 事件类型统计 */}
      {realtimeConnected && Object.keys(eventStats.byType).length > 0 && (
        <div className="px-4 py-3 border-b border-gray-200">
          <div className="text-sm font-medium text-gray-700 mb-2">事件类型分布</div>
          <div className="flex flex-wrap gap-2">
            {Object.entries(eventStats.byType)
              .sort(([,a], [,b]) => b - a)
              .slice(0, 6)
              .map(([type, count]) => (
                <div
                  key={type}
                  className="flex items-center space-x-2 px-2 py-1 bg-gray-100 rounded text-xs"
                >
                  {getEventIcon(type)}
                  <span className="text-gray-700">{getEventTypeLabel(type)}</span>
                  <span className="font-medium text-gray-900">{count}</span>
                </div>
              ))}
          </div>
        </div>
      )}

      {/* 事件日志 */}
      {showEventLog && (
        <div className="h-64 overflow-hidden">
          <div
            ref={eventLogRef}
            className="h-full overflow-y-auto px-4 py-2 space-y-2"
          >
            {realtimeEvents.length === 0 ? (
              <div className="text-center text-gray-500 py-8">
                {realtimeConnected ? '暂无事件' : '实时监控未启动'}
              </div>
            ) : (
              realtimeEvents.slice(-maxEvents).map((event, index) => (
                <div
                  key={`${event.timestamp}-${index}`}
                  className="flex items-start space-x-3 p-2 hover:bg-gray-50 rounded text-sm"
                >
                  <div className="flex-shrink-0 mt-0.5">
                    {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">
                        {getEventTypeLabel(event.event_type)}
                      </span>
                      <span className="text-xs text-gray-500">
                        {new Date(event.timestamp).toLocaleTimeString()}
                      </span>
                    </div>
                    
                    {formatEventData(event) && (
                      <div className="text-gray-600 mt-1">
                        {formatEventData(event)}
                      </div>
                    )}
                    
                    {event.data.prompt_id && (
                      <div className="text-xs text-gray-400 mt-1 font-mono">
                        ID: {event.data.prompt_id.slice(0, 8)}...
                      </div>
                    )}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      )}

      {/* 状态指示器 */}
      {!showEventLog && realtimeConnected && (
        <div className="px-4 py-3">
          <div className="text-center">
            <div className="inline-flex items-center space-x-2 text-sm text-green-600">
              <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
              <span>实时监控运行中</span>
            </div>
            {realtimeEvents.length > 0 && (
              <div className="text-xs text-gray-500 mt-1">
                最新事件: {new Date(realtimeEvents[0].timestamp).toLocaleTimeString()}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};
