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

// 自动刷新数据Hook
export function useAutoRefresh(fetchFn, interval = 30000) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const refresh = useCallback(async () => {
    try {
      setLoading(true);
      const result = await fetchFn();
      setData(result);
      setError(null);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [fetchFn]);

  useEffect(() => {
    refresh();
    
    const timer = setInterval(refresh, interval);
    
    return () => clearInterval(timer);
  }, [refresh, interval]);

  return { data, loading, error, refresh };
}

// 格式化时间
export function formatTime(dateString) {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
}

// 格式化延迟
export function formatLatency(ms) {
  if (ms === undefined || ms === null) return '-';
  if (ms < 1000) return `${ms}ms`;
  return `${(ms / 1000).toFixed(2)}s`;
}

// 格式化可用率
export function formatUptime(uptime) {
  if (uptime === undefined || uptime === null) return '-';
  return `${uptime.toFixed(2)}%`;
}

// 获取状态颜色类名
export function getStatusColor(isUp, statusCode) {
  if (!isUp) return 'text-red-500 bg-red-100';
  if (statusCode >= 200 && statusCode < 300) return 'text-green-500 bg-green-100';
  if (statusCode >= 300 && statusCode < 400) return 'text-yellow-500 bg-yellow-100';
  return 'text-red-500 bg-red-100';
}

// 获取可用率颜色
export function getUptimeColor(uptime) {
  if (uptime >= 99) return 'text-green-500';
  if (uptime >= 95) return 'text-green-400';
  if (uptime >= 90) return 'text-yellow-500';
  if (uptime >= 80) return 'text-orange-500';
  return 'text-red-500';
}

// 获取延迟颜色
export function getLatencyColor(ms) {
  if (ms < 200) return 'text-green-500';
  if (ms < 500) return 'text-green-400';
  if (ms < 1000) return 'text-yellow-500';
  if (ms < 2000) return 'text-orange-500';
  return 'text-red-500';
}
