import React, {useMemo, useCallback} from 'react';
import {createContext, ReactNode, useContext, useState} from 'react';

interface IValueProps {
  animating?: boolean;
}

export interface ILoaderProps {
  loader: IValueProps;
  showLoader: () => void;
  hideLoader: () => void;
}

const contextDefaultValues: ILoaderProps = {
  loader: {animating: false},
  showLoader: () => {},
  hideLoader: () => {},
};

const LoaderContext = createContext<ILoaderProps>(contextDefaultValues);

export const LoaderProvider = ({children}: {children: ReactNode}) => {
  const [loader, setLoader] = useState(contextDefaultValues.loader);

  const showLoader = useCallback(
    () => setLoader({...loader, animating: true}),
    [loader],
  );
  const hideLoader = useCallback(
    () => setLoader({...loader, animating: false}),
    [loader],
  );

  return (
    <LoaderContext.Provider
      value={useMemo(
        () => ({
          loader,

          showLoader,
          hideLoader,
        }),
        [loader, showLoader, hideLoader],
      )}>
      {children}
    </LoaderContext.Provider>
  );
};

export default () => useContext(LoaderContext);
