import React, { useReducer } from 'react';
import { AppContextProviderProps, AppContextProps } from 'common/types';
import { initialState } from 'context/inital-state';
import { appReducer } from './reducer';
import { navigate } from '@reach/router';

export const AppContext = React.createContext({} as AppContextProps);

export const AppContextProvider = ({ children }: AppContextProviderProps) => {
  const [state, dispatch] = useReducer(appReducer, initialState);

  const isUserLogged = !!Object.keys(
    JSON.parse(localStorage.getItem('user') || '{}')
  ).length;

  if (!isUserLogged) {
    navigate('/login');
  }

  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
};
