import React, {
  createContext,
  Dispatch,
  FC,
  ReactElement,
  SetStateAction,
  useContext,
  useState,
} from 'react';

import { USER_ROLE_UPDATE } from '../constants/appLoading';

type AppLoading = string[];
type AppLoadingState = [AppLoading, Dispatch<SetStateAction<AppLoading>>];

const AppLoadingContext = createContext<AppLoadingState>(undefined as never);

type props = {
  children: ReactElement;
};

export const AppLoadingProvider: FC<props> = ({ children }) => {
  const appState = useState<AppLoading>([USER_ROLE_UPDATE]);

  return <AppLoadingContext.Provider value={appState}>{children}</AppLoadingContext.Provider>;
};

export const useAppLoading = () => {
  const [appLoading, setAppIsLoading] = useContext(AppLoadingContext);
  return [!!appLoading.length, setAppIsLoading];
};

export const useUpdateLoadingStatus = () => {
  const [, setAppIsLoading] = useContext(AppLoadingContext);
  return (isLoading: boolean, loadingSource: string) => {
    if (isLoading) {
      setAppIsLoading(prev => (prev.includes(loadingSource) ? prev : [...prev, loadingSource]));
    } else {
      setAppIsLoading(prev => prev.filter(item => item !== loadingSource));
    }
  };
};
