import {RefObject, useEffect, useRef} from 'react';
import {TextInputType} from '@components';
import {useReactionDialogShown} from '@modules/chats/store';

// When the reactions dialog is shown, we want to blur the input
// to avoid the keyboard overlapping the dialog. When the dialog
// is hidden, we want to restore the focus to the input if it
// was focused before.
export const useKeyboardHandlerOnReactionsDialog = (
  inputRef: RefObject<Nullable<TextInputType>>,
) => {
  const isShown = useReactionDialogShown();

  const isInputFocusedSavedState = useRef(false);

  useEffect(() => {
    if (!inputRef.current) {
      return;
    }
    // Hide keyboard when the dialog is shown
    if (isShown) {
      const isFocused = inputRef.current.isFocused();
      isInputFocusedSavedState.current = isFocused;
      if (isFocused) {
        inputRef.current.blur();
      }
    } else {
      // Show keyboard if it was open before the dialog was shown
      if (isInputFocusedSavedState.current) {
        inputRef.current.focus();
      }
    }
  }, [isShown, inputRef]);
};
