import { useEffect, useRef } from 'react'

export const useAutoFocus = <T extends HTMLElement>(autoFocus?: boolean) => {
  const ref = useRef<T>(null)

  useEffect(() => {
    if (!autoFocus || !ref.current) return

    const attemptFocus = (attempts = 0): void => {
      if (attempts > 20 || !ref.current) return

      const focusable = ref.current.querySelector<HTMLElement>(
        'button:not([disabled]), [tabindex]:not([tabindex="-1"])'
      )

      if (focusable) {
        focusable.focus()
      } else {
        requestAnimationFrame(() => attemptFocus(attempts + 1))
      }
    }

    requestAnimationFrame(() => attemptFocus())
  }, [autoFocus])

  return ref
}
