import {TableSearchContext, useContextSection} from '@hooks';
import {Context} from 'use-context-selector';
import {useCallback} from 'react';
import {useBoolean, useLatest} from 'ahooks';

export function useTableSearchToolEvents<T>(
  context: Context<TableSearchContext<T>>,
  payload: T,
  options: {searchCallback?: () => void; resetCallback?: () => void} = {},
) {
  const dispatch = useContextSection(context, state => state[1]);
  const {searchCallback, resetCallback} = options;
  const callbackFn = useLatest(searchCallback);
  const resetCallbackFn = useLatest(resetCallback);

  const onSearch = useCallback(
    function () {
      callbackFn.current?.();

      dispatch({type: 'SEARCH', payload});
    },
    [callbackFn, dispatch, payload],
  );

  const onReset = useCallback(
    function () {
      resetCallbackFn.current?.();
      dispatch({type: 'RESET'});
    },
    [dispatch, resetCallbackFn],
  );

  const [visible, {setTrue, setFalse}] = useBoolean();

  return [
    visible,
    {onSearch, onReset, onShowModal: setTrue, onCloseModal: setFalse},
  ] as const;
}
