import {useLocation, useNavigate, NavigateOptions} from 'react-router'

import {DATA_NAVIGATION_TYPE_ATTRIBUTE} from '../../types'

type UseNavigateWithTransitionReturns = (
  to: string | number,
  options?: NavigateOptions
) => void | Promise<void>

export function useNavigateWithTransition(): UseNavigateWithTransitionReturns {
  const navigate = useNavigate()
  const location = useLocation()

  const transitionNavigate = (
    to: string | number,
    options?: NavigateOptions
  ) => {
    if (typeof to === 'number') {
      // Delta navigation - no options parameter
      if (document.startViewTransition) {
        const transition = document.startViewTransition(() => {
          navigate(to)
        })

        transition.finished
          .then(() => {
            document.documentElement.removeAttribute(
              DATA_NAVIGATION_TYPE_ATTRIBUTE
            )
          })
          .catch(error => {
            console.error('View transition error:', error)
          })
      } else {
        return navigate(to)
      }
      return
    }

    const isSameRoute = to === location.pathname

    // Path navigation - with options
    if (document.startViewTransition) {
      const transition = document.startViewTransition(() => {
        navigate(to, {
          preventScrollReset: true,
          replace: isSameRoute,
          ...options,
        })
      })

      transition.finished
        .then(() => {
          document.documentElement.removeAttribute(
            DATA_NAVIGATION_TYPE_ATTRIBUTE
          )
        })
        .catch(error => {
          console.error('View transition error:', error)
        })
    } else {
      return navigate(to, options)
    }
  }

  return transitionNavigate
}
