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

interface UseAutoRefreshOptions {
  callback: () => void | Promise<void>;
  intervalMs: number;
  enabled?: boolean;
  immediate?: boolean;
}

/**
 * Custom hook for auto-refreshing data at regular intervals.
 * Cleans up automatically on unmount.
 */
export function useAutoRefresh({
  callback,
  intervalMs,
  enabled = true,
  immediate = true,
}: UseAutoRefreshOptions) {
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const isMountedRef = useRef(true);

  const executeCallback = useCallback(async () => {
    if (isMountedRef.current && enabled) {
      await callback();
    }
  }, [callback, enabled]);

  useEffect(() => {
    isMountedRef.current = true;

    if (immediate) {
      executeCallback();
    }

    if (enabled) {
      intervalRef.current = setInterval(executeCallback, intervalMs);
    }

    return () => {
      isMountedRef.current = false;
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    };
  }, [callback, intervalMs, enabled, immediate, executeCallback]);

  const refresh = useCallback(() => {
    executeCallback();
  }, [executeCallback]);

  return { refresh };
}
