'use client'

import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { type ComponentProps, startTransition } from 'react'
import { useProgressBarContext } from '../hooks/use-progerss-bar-context'

export const ProgressBarLink = (
  { href, children, ...rest }: ComponentProps<typeof Link>
) => {
  const progress = useProgressBarContext()
  const router = useRouter()
  const pathname = usePathname()

  return (
    <Link
      href={href}
      onClick={(e) => {
        e.preventDefault()
        if (pathname === href) {
          return
        }
        progress.start()

        startTransition(() => {
          router.push(href.toString())
          progress.done()
        })
      }}
      {...rest}
    >
      {children}
    </Link>
  )
}
