import { useState, useEffect, useRef } from 'react';

interface WebSocketMetrics {
  frontend: {
    messagesPerSecond: number;
    totalMessages: number;
    lastUpdate: Date;
  };
  backend: {
    messagesPerSecond: number;
    totalMessages: number;
    lastUpdate: Date;
  };
  dataService: {
    messagesPerSecond: number;
    totalMessages: number;
    lastUpdate: Date;
  };
}

interface WebSocketMessage {
  type: string;
  service?: string;
  data?: any;
  timestamp?: number;
}

/**
 * 실시간 WebSocket 메트릭 Hook
 * 
 * WebSocket 메시지를 실시간으로 수신하여 초당 메시지 수를 계산합니다.
 */
export const useRealtimeWebSocketMetrics = () => {
  const [metrics, setMetrics] = useState<WebSocketMetrics>({
    frontend: { messagesPerSecond: 0, totalMessages: 0, lastUpdate: new Date() },
    backend: { messagesPerSecond: 0, totalMessages: 0, lastUpdate: new Date() },
    dataService: { messagesPerSecond: 0, totalMessages: 0, lastUpdate: new Date() },
  });

  const [isConnected, setIsConnected] = useState(false);
  const wsRef = useRef<WebSocket | null>(null);
  
  // 메시지 카운터 (1초 단위 슬라이딩 윈도우)
  const messageCountersRef = useRef({
    frontend: [] as number[],
    backend: [] as number[],
    dataService: [] as number[],
  });

  // 총 메시지 카운터
  const totalCountersRef = useRef({
    frontend: 0,
    backend: 0,
    dataService: 0,
  });

  useEffect(() => {
    // WebSocket 연결
    const connectWebSocket = () => {
      const wsUrl = process.env.REACT_APP_WS_URL || 'ws://localhost:8083/ws/realtime';
      
      try {
        const ws = new WebSocket(wsUrl);
        wsRef.current = ws;

        ws.onopen = () => {
          console.log('[WebSocket Metrics] Connected to', wsUrl);
          setIsConnected(true);
          
          // 구독 메시지 전송
          ws.send(JSON.stringify({
            type: 'subscribe',
            markets: ['KRW-BTC'], // 샘플 마켓
            timeframes: ['1m'],
          }));
        };

        ws.onmessage = (event) => {
          try {
            const message: WebSocketMessage = JSON.parse(event.data);
            const now = Date.now();
            
            // 메시지 타입에 따라 서비스 구분
            let service: 'frontend' | 'backend' | 'dataService' = 'backend';
            
            if (message.type === 'candle' || message.type === 'ticker') {
              service = 'backend'; // Upbit에서 수신
            } else if (message.type === 'indicator' || message.type === 'chart') {
              service = 'frontend'; // Frontend로 송신
            } else if (message.type === 'process') {
              service = 'dataService'; // Data Service 처리
            }
            
            // 메시지 카운트
            messageCountersRef.current[service].push(now);
            totalCountersRef.current[service]++;
            
            // 1초 이전 메시지 제거 (슬라이딩 윈도우)
            const oneSecondAgo = now - 1000;
            messageCountersRef.current[service] = messageCountersRef.current[service].filter(
              (timestamp) => timestamp > oneSecondAgo
            );
          } catch (error) {
            console.error('[WebSocket Metrics] Message parse error:', error);
          }
        };

        ws.onerror = (error) => {
          console.error('[WebSocket Metrics] Error:', error);
          setIsConnected(false);
        };

        ws.onclose = () => {
          console.log('[WebSocket Metrics] Disconnected');
          setIsConnected(false);
          
          // 3초 후 재연결 시도
          setTimeout(() => {
            if (wsRef.current?.readyState === WebSocket.CLOSED) {
              connectWebSocket();
            }
          }, 3000);
        };
      } catch (error) {
        console.error('[WebSocket Metrics] Connection error:', error);
        setIsConnected(false);
      }
    };

    connectWebSocket();

    // 메트릭 업데이트 (100ms마다)
    const updateInterval = setInterval(() => {
      const now = Date.now();
      const oneSecondAgo = now - 1000;

      // 각 서비스별로 1초 내 메시지 수 계산
      const frontendCount = messageCountersRef.current.frontend.filter(
        (t) => t > oneSecondAgo
      ).length;
      const backendCount = messageCountersRef.current.backend.filter(
        (t) => t > oneSecondAgo
      ).length;
      const dataServiceCount = messageCountersRef.current.dataService.filter(
        (t) => t > oneSecondAgo
      ).length;

      setMetrics({
        frontend: {
          messagesPerSecond: frontendCount,
          totalMessages: totalCountersRef.current.frontend,
          lastUpdate: new Date(),
        },
        backend: {
          messagesPerSecond: backendCount,
          totalMessages: totalCountersRef.current.backend,
          lastUpdate: new Date(),
        },
        dataService: {
          messagesPerSecond: dataServiceCount,
          totalMessages: totalCountersRef.current.dataService,
          lastUpdate: new Date(),
        },
      });
    }, 100); // 100ms마다 업데이트 (부드러운 애니메이션)

    // 클린업
    return () => {
      clearInterval(updateInterval);
      if (wsRef.current) {
        wsRef.current.close();
        wsRef.current = null;
      }
    };
  }, []);

  return {
    metrics,
    isConnected,
  };
};
