import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  ReactNode,
} from 'react';
import { useLocation } from 'react-router-dom';

type NavigationLoadingContextValue = {
  isLoading: boolean;
  setIsLoading: (loading: boolean) => void;
};

const NavigationLoadingContext = createContext<NavigationLoadingContextValue | undefined>(undefined);

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

interface NavigationLoadingProviderProps {
  children: ReactNode;
}

export const NavigationLoadingProvider: React.FC<NavigationLoadingProviderProps> = ({ children }) => {
  const [isLoading, setIsLoading] = useState(false);
  const location = useLocation();

  useEffect(() => {
    // Show preloader when route changes
    setIsLoading(true);
    
    // Hide preloader after a short delay to allow page to render
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 300);

    return () => clearTimeout(timer);
  }, [location.pathname]);

  return (
    <NavigationLoadingContext.Provider
      value={{
        isLoading,
        setIsLoading,
      }}
    >
      {children}
    </NavigationLoadingContext.Provider>
  );
};

