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

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

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

// #region 内容管理
type State = {
  startTime: string;
  endTime: string;
  id: string;
};

type Action =
| {type: 'SET_ID', payload: string}
| {type: 'RESET', payload: Pick<State, 'id'>}
| {type: 'SEARCH', payload: Omit<State, 'id'>};

export function initState(initId?: string): State {
  return {startTime: '', endTime: '', id: initId ?? ''};
}

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

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

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

export const context = createContext<ReturnType<typeof useContextReducer>>(
  [initState(), () => null],
);
// #endregion
