import { type RefObject, useEffect, useState } from "react"

interface UseScrollToTopProps {
  threshold: number
  elementRef?: RefObject<HTMLElement | null>
  refScrollable?: boolean
}

export function useScrollToTop({
  threshold,
  elementRef,
  refScrollable,
}: UseScrollToTopProps) {
  const [showBackToTop, setShowBackToTop] = useState(false)

  useEffect(() => {
    const element =
      refScrollable && elementRef?.current ? elementRef?.current : window

    function handleScroll() {
      let position = window.scrollY
      if (elementRef?.current) {
        position = refScrollable
          ? elementRef.current.scrollTop
          : elementRef.current.getBoundingClientRect().top * -1
      }
      setShowBackToTop(position > threshold)
    }

    element.addEventListener("scroll", handleScroll, { passive: true })
    return () => element.removeEventListener("scroll", handleScroll)
  }, [threshold, elementRef, refScrollable])

  function scrollToTop() {
    if (elementRef?.current) {
      if (refScrollable) {
        elementRef.current.scrollTo({ top: 0, behavior: "smooth" })
      }
      window.scrollTo({ top: elementRef.current.offsetTop, behavior: "smooth" })
    } else {
      window.scrollTo({ top: 0, behavior: "smooth" })
    }
  }

  return { showBackToTop, scrollToTop }
}
