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

interface LoadingContextType {
  // Global loading (for API calls, etc.)
  globalLoading: boolean;
  globalLoadingText: string;
  setGlobalLoading: (loading: boolean, text?: string) => void;
  
  // Navigation loading (for route changes)
  navigationLoading: boolean;
  setNavigationLoading: (loading: boolean) => void;
  
  // Combined loading state (true if either is loading)
  isLoading: boolean;
}

const LoadingContext = createContext<LoadingContextType | undefined>(undefined);

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

// Backward compatibility hooks
// eslint-disable-next-line react-refresh/only-export-components
export const useGlobalLoading = () => {
  const { globalLoading, globalLoadingText, setGlobalLoading } = useLoading();
  return {
    isLoading: globalLoading,
    loadingText: globalLoadingText,
    setLoading: setGlobalLoading,
  };
};

// eslint-disable-next-line react-refresh/only-export-components
export const useNavigationLoading = () => {
  const { navigationLoading, setNavigationLoading } = useLoading();
  return {
    isLoading: navigationLoading,
    setNavigationLoading,
  };
};

interface LoadingProviderProps {
  children: ReactNode;
}

export const LoadingProvider: React.FC<LoadingProviderProps> = ({ children }) => {
  const [globalLoading, setGlobalLoadingState] = useState(false);
  const [globalLoadingText, setGlobalLoadingText] = useState('Loading...');
  const [navigationLoading, setNavigationLoadingState] = useState(false);

  // Set global loading with optional text
  const setGlobalLoading = useCallback((loading: boolean, text: string = 'Loading...') => {
    setGlobalLoadingState(loading);
    setGlobalLoadingText(text);
  }, []);

  // Set navigation loading
  const setNavigationLoading = useCallback((loading: boolean) => {
    setNavigationLoadingState(loading);
  }, []);

  // Combined loading state
  const isLoading = globalLoading || navigationLoading;

  const value: LoadingContextType = {
    globalLoading,
    globalLoadingText,
    setGlobalLoading,
    navigationLoading,
    setNavigationLoading,
    isLoading,
  };

  return (
    <LoadingContext.Provider value={value}>
      {children}
      <GlobalLoading isLoading={globalLoading} text={globalLoadingText} />
    </LoadingContext.Provider>
  );
};

