import {RefObject, useCallback} from 'react'

import {useShopActions} from '../../internal/useShopActions'

export interface UseKeyboardAvoidingViewReturns {
  /**
   * function to call when the input is focused
   */
  onFocus: (ref: RefObject<HTMLElement | null>) => void
  /**
   * function to call when the input is blurred
   */
  onBlur: () => void
}

export const useKeyboardAvoidingView = (): UseKeyboardAvoidingViewReturns => {
  const {translateContentUp, translateContentDown} = useShopActions()

  const onFocus = useCallback(
    (ref: RefObject<HTMLElement | null>) => {
      if (ref.current) {
        const rect = ref.current.getBoundingClientRect()
        translateContentUp({inputYPosition: rect.bottom})
      }
    },
    [translateContentUp]
  )

  const onBlur = useCallback(() => {
    translateContentDown()
  }, [translateContentDown])

  return {
    onFocus,
    onBlur,
  }
}
