import { useEffect, useRef } from 'react';

export function useInterval(callback: () => void, delay: number | null) {
  const savedCallback = useRef(callback);

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    if (delay === null) return;
    
    const id = setInterval(() => savedCallback.current(), delay);
    return () => clearInterval(id);
  }, [delay]);
}

export function usePolling<T>(
  fetchFn: () => Promise<T>,
  intervalMs: number,
  enabled: boolean = true
) {
  const savedFetch = useRef(fetchFn);

  useEffect(() => {
    savedFetch.current = fetchFn;
  }, [fetchFn]);

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

    const performFetch = async () => {
      try {
        await savedFetch.current();
      } catch (error) {
        console.error('Polling fetch failed:', error);
      }
    };

    performFetch();
    const id = setInterval(performFetch, intervalMs);
    return () => clearInterval(id);
  }, [intervalMs, enabled]);
}

export const statusColors: Record<string, 'success' | 'error' | 'primary' | 'warning' | 'default'> = {
  completed: 'success',
  failed: 'error',
  running: 'primary',
  pending: 'warning',
};

export function getStatusColor(status: string): 'success' | 'error' | 'primary' | 'warning' | 'default' {
  return statusColors[status] || 'default';
}

export function formatDate(dateString: string | null): string {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleString();
}
