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

// #region 查询条件
type State = {
  name: string;
};

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

function initState(name?: string): State {
  return {name: name ?? ''};
}

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

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

export function useContextReducer(init?: string) {
  return useReducer(reducer, initState(init));
}

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

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

/** 搜索状态管理 */
export const searchContext = createSearchContext();
