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

// #region 整体弹窗管理
type State = {
  name: string;
};

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

function initState(): State {
  return {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() {
  return useReducer(reducer, initState());
}

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

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

// #region pId管理
export function usePIdContextState(init: string) {
  return useState(init);
}

export const pIdContext = createContext<ReturnType<typeof usePIdContextState>>(['', () => null]);
// #endregion

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