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

export interface UseListDataReturn<T> {
  data: T[];
  loading: boolean;
  refresh: () => Promise<void>;
}

export function useListData<T>(fetchFn: () => Promise<T[]>, autoFetch = true): UseListDataReturn<T> {
  const [data, setData] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const fetchFnRef = useRef(fetchFn);
  fetchFnRef.current = fetchFn;

  const refresh = useCallback(async () => {
    setLoading(true);
    try {
      const result = await fetchFnRef.current();
      setData(result);
    } catch {
      setData([]);
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    if (autoFetch) {
      refresh();
    }
  }, [refresh, autoFetch]);

  return { data, loading, refresh };
}
