import { useQueryClient } from '@tanstack/react-query';
import { createContext, useCallback, useContext, useState } from 'react';

type RefreshContextType = {
  refreshing: boolean;
  onRefresh: () => Promise<void>;
};

const RefreshContext = createContext<RefreshContextType | null>(null);

export function RefreshProvider({ children }: { children: React.ReactNode }) {
  const queryClient = useQueryClient();
  const [refreshing, setRefreshing] = useState(false);

  const onRefresh = useCallback(async () => {
    if (refreshing) return;

    setRefreshing(true);
    try {
      await queryClient.refetchQueries();
    } catch (err) {
      console.error('Global refresh error:', err);
    } finally {
      setRefreshing(false);
    }
  }, [queryClient, refreshing]);

  return (
    <RefreshContext.Provider value={{ refreshing, onRefresh }}>{children}</RefreshContext.Provider>
  );
}

export function useGlobalRefresh() {
  const ctx = useContext(RefreshContext);
  if (!ctx) throw new Error('useGlobalRefresh must be used inside RefreshProvider');
  return ctx;
}
