import { useState, useEffect, useCallback } from 'react';
import type { ServerConfig, ServerStatus } from '../types';
import { fetchServerMetrics } from '../api/monitor';

export const useServerMonitor = (servers: ServerConfig[], interval: number = 2000) => {
  const [statuses, setStatuses] = useState<Record<string, ServerStatus>>({});

  const fetchMetrics = useCallback(async (server: ServerConfig) => {
    if (!server.enabled) {
      return;
    }

    try {
      const metrics = await fetchServerMetrics(server.url);
      setStatuses(prev => ({
        ...prev,
        [server.id]: {
          serverId: server.id,
          online: true,
          metrics,
          lastUpdate: Date.now(),
        },
      }));
    } catch (error) {
      setStatuses(prev => ({
        ...prev,
        [server.id]: {
          serverId: server.id,
          online: false,
          error: error instanceof Error ? error.message : 'Unknown error',
          lastUpdate: Date.now(),
        },
      }));
    }
  }, []);

  useEffect(() => {
    // Initial fetch
    servers.forEach(server => {
      if (server.enabled) {
        fetchMetrics(server);
      }
    });

    // Set up polling
    const timer = setInterval(() => {
      servers.forEach(server => {
        if (server.enabled) {
          fetchMetrics(server);
        }
      });
    }, interval);

    return () => clearInterval(timer);
  }, [servers, interval, fetchMetrics]);

  return statuses;
};
