import { type RefObject, useEffect, useRef } from 'react'

export const useFocus = (
  /** This prop is needed to ensure the element is visible */
  isVisible: boolean,
): RefObject<HTMLInputElement> => {
  const ref = useRef<HTMLInputElement>(null)
  const inputTimeout = useRef<ReturnType<typeof setTimeout>>(undefined)

  useEffect(() => {
    if (isVisible && ref.current) {
      inputTimeout.current = setTimeout(() => {
        ref.current?.focus()
      }, 250)
    }
    return () => {
      inputTimeout.current = undefined
    }
  }, [isVisible])

  return ref as RefObject<HTMLInputElement>
}
