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

export type TableSearchAction<S> =
  | {type: 'SEARCH'; payload: Partial<S>}
  | {type: 'RESET'};

type InitStateType = Readonly<Record<string, unknown>>;

export function useTableSearchContextReducer<S extends InitStateType>(init: S) {
  function initState() {
    return {...init};
  }

  function reducer(state: S, action: TableSearchAction<S>): S {
    const {type} = action;

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

  return useReducer(reducer, initState());
}

export type TableSearchContext<S> = [S, Dispatch<TableSearchAction<S>>];

export function createTableSearchContext<S extends InitStateType>(state: S) {
  return createContext<TableSearchContext<S>>([{...state}, () => null]);
}
