import React, { createContext, useContext, useReducer } from 'react';

import initialMainState from './initialMainState';
import initialPdfState from './initialPdfState';
import initialSearchState from './initialSearchState';

import reducers from '../reducers';
import applyMiddleware from '../reducers/middleware';

export type StateType = MainStateType & PdfStateType & SearchStateType;

type IContextProps = [StateType, DispatchType];

export const initialState = {
  ...initialMainState,
  ...initialPdfState,
  ...initialSearchState,
};

export const StateContext = createContext({} as IContextProps);

export const StoreProvider = ({
  children,
}: {
  children: React.ReactNode;
}): React.ReactElement => {
  const [state, dispatch] = useReducer(reducers, initialState);
  const enhancedDispatch = applyMiddleware(dispatch);

  return (
    <StateContext.Provider value={[state, enhancedDispatch]}>
      {children}
    </StateContext.Provider>
  );
};

export default (): IContextProps => useContext(StateContext);
