import React, { createContext, useContext, useState, ReactNode } from 'react';
import GlobalLoading from '../components/GlobalLoading';

interface GlobalLoadingContextType {
  setLoading: (loading: boolean, text?: string) => void;
  isLoading: boolean;
  loadingText: string;
}

const GlobalLoadingContext = createContext<GlobalLoadingContextType | undefined>(undefined);

// eslint-disable-next-line react-refresh/only-export-components
export const useGlobalLoading = () => {
  const context = useContext(GlobalLoadingContext);
  if (!context) {
    throw new Error('useGlobalLoading must be used within GlobalLoadingProvider');
  }
  return context;
};

interface GlobalLoadingProviderProps {
  children: ReactNode;
}

export const GlobalLoadingProvider: React.FC<GlobalLoadingProviderProps> = ({ children }) => {
  const [isLoading, setIsLoading] = useState(false);
  const [loadingText, setLoadingText] = useState('Loading...');

  const setLoading = (loading: boolean, text: string = 'Loading...') => {
    setIsLoading(loading);
    setLoadingText(text);
  };

  return (
    <GlobalLoadingContext.Provider value={{ setLoading, isLoading, loadingText }}>
      {children}
      <GlobalLoading isLoading={isLoading} text={loadingText} />
    </GlobalLoadingContext.Provider>
  );
};

