// React hook for WebSocket connection

import { useEffect, useState, useCallback } from 'react';
import { getWebSocketClient } from '../api/websocket';
import type { WebSocketMessage, Event, Statistics } from '../types';

interface UseWebSocketReturn {
  isConnected: boolean;
  latestEvent: Event | null;
  latestStatistics: Statistics | null;
  send: (message: any) => void;
}

export const useWebSocket = (
  onEvent?: (event: Event) => void,
  onStats?: (stats: Statistics) => void
): UseWebSocketReturn => {
  const [isConnected, setIsConnected] = useState(false);
  const [latestEvent, setLatestEvent] = useState<Event | null>(null);
  const [latestStatistics, setLatestStatistics] = useState<Statistics | null>(null);

  useEffect(() => {
    const wsClient = getWebSocketClient();

    // Handle connection status changes
    const unsubscribeConnection = wsClient.onConnectionChange((connected) => {
      setIsConnected(connected);
    });

    // Handle incoming messages
    const unsubscribeMessage = wsClient.onMessage((message: WebSocketMessage) => {
      switch (message.type) {
        case 'event_created':
          if (message.event) {
            setLatestEvent(message.event);
            onEvent?.(message.event);
          }
          if (message.statistics) {
            setLatestStatistics(message.statistics);
            onStats?.(message.statistics);
          }
          break;

        case 'stats_updated':
          if (message.statistics) {
            setLatestStatistics(message.statistics);
            onStats?.(message.statistics);
          }
          break;

        case 'stats_reset':
          // Reset local state
          setLatestEvent(null);
          setLatestStatistics({
            total_events: 0,
            total_tools_used: 0,
            total_agents: 0,
            total_sessions: 0,
            last_updated: Date.now() / 1000,
          });
          onStats?.({
            total_events: 0,
            total_tools_used: 0,
            total_agents: 0,
            total_sessions: 0,
            last_updated: Date.now() / 1000,
          });
          break;

        case 'connection_status':
          console.log('Connection status:', message.message);
          break;

        case 'pong':
          // Heartbeat response
          break;

        default:
          console.log('Unknown message type:', message.type);
      }
    });

    // Set initial connection status
    setIsConnected(wsClient.isConnected());

    // Cleanup
    return () => {
      unsubscribeConnection();
      unsubscribeMessage();
    };
  }, [onEvent, onStats]);

  const send = useCallback((message: any) => {
    const wsClient = getWebSocketClient();
    wsClient.send(message);
  }, []);

  return {
    isConnected,
    latestEvent,
    latestStatistics,
    send,
  };
};

export default useWebSocket;
