import {createPageContext} from '@hooks';
import {Dispatch, useReducer} from 'react';
import {createContext} from 'use-context-selector';

// #region 搜索条件
type State = {
  name: string,
  isSearching: boolean,
};

type Action =
| {type: 'SEARCH', payload: Omit<State, 'isSearching'>}
| {type: 'CHANGE_SEARCH_STATE', payload: State['isSearching']}
| {type: 'RESET'};

function initState(): State {
  return {name: '', isSearching: false};
}

function reducer(state: State, action: Action): State {
  const {type} = action;

  switch (type) {
    case 'SEARCH':
      return {...state, ...action.payload};
    case 'CHANGE_SEARCH_STATE':
      return {...state, isSearching: action.payload};
    case 'RESET':
      return initState();
    default:
      return state;
  }
}

export function useContextReducer() {
  return useReducer(reducer, initState());
}

export const context = createContext<[State, Dispatch<Action>]>([initState(), () => null]);
// #endregion

/** 页码管理 */
export const pageContext = createPageContext();
