// useRealtimeUpdates Hook
import { useEffect, useRef } from 'react';
import { useQueryClient } from '@tanstack/react-query';

interface UseRealtimeUpdatesOptions {
  queryKey: string[];
  interval?: number;
  enabled?: boolean;
  onUpdate?: (data: any) => void;
}

/**
 * Hook for real-time updates using polling
 * Can be extended to use WebSocket when backend supports it
 */
export function useRealtimeUpdates({
  queryKey,
  interval = 10000, // 10 seconds default
  enabled = true,
  onUpdate,
}: UseRealtimeUpdatesOptions) {
  const queryClient = useQueryClient();
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (!enabled) {
      return;
    }

    const refetch = async () => {
      try {
        const data = await queryClient.fetchQuery({ queryKey });
        if (onUpdate) {
          onUpdate(data);
        }
      } catch (error) {
        console.error('Realtime update failed:', error);
      }
    };

    // Initial fetch
    refetch();

    // Set up interval
    intervalRef.current = setInterval(refetch, interval);

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [queryKey, interval, enabled, onUpdate, queryClient]);

  return {
    stop: () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    },
    start: () => {
      if (!intervalRef.current && enabled) {
        intervalRef.current = setInterval(async () => {
          await queryClient.fetchQuery({ queryKey });
        }, interval);
      }
    },
  };
}

/**
 * Hook for WebSocket real-time updates (when backend supports it)
 */
export function useWebSocketUpdates(
  url: string,
  onMessage: (data: any) => void,
  enabled: boolean = true
) {
  const wsRef = useRef<WebSocket | null>(null);

  useEffect(() => {
    if (!enabled) {
      return;
    }

    const ws = new WebSocket(url);

    ws.onopen = () => {
      console.log('WebSocket connected');
    };

    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        onMessage(data);
      } catch (error) {
        console.error('Failed to parse WebSocket message:', error);
      }
    };

    ws.onerror = (error) => {
      console.error('WebSocket error:', error);
    };

    ws.onclose = () => {
      console.log('WebSocket disconnected');
    };

    wsRef.current = ws;

    return () => {
      if (wsRef.current) {
        wsRef.current.close();
        wsRef.current = null;
      }
    };
  }, [url, onMessage, enabled]);

  return {
    send: (data: any) => {
      if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
        wsRef.current.send(JSON.stringify(data));
      }
    },
    close: () => {
      if (wsRef.current) {
        wsRef.current.close();
        wsRef.current = null;
      }
    },
  };
}

