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

// #region 整体弹窗管理
type State = {
  name: string;
  onClose: null | (() => void);
};

type Action =
| {type: 'SEARCH', payload: {name: string}}
| {type: 'RESET'}
| {type: 'SET_CLOSE', payload: () => void | null};

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

  switch (type) {
    case 'SEARCH': {
      const next = produce(state, function(draft) {
        draft.name = action.payload.name;
      });

      return next;
    }
    case 'SET_CLOSE': {
      const next = produce(state, function(draft) {
        draft.onClose = action.payload;
      });

      return next;
    }
    case 'RESET':
      return {name: '', onClose: null};
    default:
      return state;
  }
}

function initState(onClose?: () => void): State {
  return {name: '', onClose: onClose ?? null};
}

export function useContextReducer(onClose: () => void) {
  return useReducer(reducer, initState(onClose));
}

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
