import { useRef } from 'react'

import { useEventListener } from 'hooks'

type Args = {
  onClick: (event?: MouseEvent) => void,
}

export const useOutsideClickEffect = ({
  onClick,
}: Args) => {
  const wrapperRef = useRef<HTMLDivElement>(null)
  const handleOutsideClick = (e: MouseEvent) => {
    const targetNode = e.target instanceof Node
      ? e.target
      : null

    /** деструктуризация wrapperRef не сработает, ссылка на реф теряется */
    if (!wrapperRef.current?.contains(targetNode)) {
      onClick(e)
    }
  }

  const onKeyPress = (e: KeyboardEvent) => {
    if (e.key === 'Escape') {
      onClick()
    }
  }

  useEventListener({ callback: handleOutsideClick, event: 'click' })
  useEventListener({ callback: onKeyPress, event: 'keydown' })

  return wrapperRef
}
