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

import initialMainState, {
  StateType as MainStateType,
} from './initialMainState';
import initialPdfState, { StateType as PdfStateType } from './initialPdfState';
import initialSearchState, {
  StateType as SearchStateType,
} from './initialSearchState';

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

type StateType = MainStateType & PdfStateType & SearchStateType;

type IContextProps = [StateType, ({ type }: { type: string }) => void];

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(state, dispatch);

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

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