"use client"
import NextLink from "next/link"
import { usePathname, useRouter } from "next/navigation"
import { startTransition, useCallback, useEffect } from "react"

import useRouterTransitionStore from "@/stores/router-transition"

import { trackClick, trackPageViewStart } from "@/utils/tracking"

import { linkVariants } from "./variants"

import type { LinkProps } from "./link"

export default function Link({
  active,
  className,
  color,
  href,
  partialMatch = false,
  textDecoration,
  size,
  scroll = true,
  prefetch,
  variant,
  trackingId,
  onClick,
  ...props
}: LinkProps) {
  const currentPageSlug = usePathname()
  let isActive = active || currentPageSlug === href

  if (partialMatch && !isActive) {
    isActive = currentPageSlug === href
  }

  const classNames = linkVariants({
    active: isActive,
    className,
    textDecoration,
    color,
    size,
    variant,
  })

  const router = useRouter()

  const startRouterTransition = useRouterTransitionStore(
    (state) => state.startRouterTransition
  )

  const trackClickById = useCallback(() => {
    if (trackingId) {
      trackClick(trackingId)
    }
  }, [trackingId])

  return (
    <NextLink
      scroll={scroll}
      prefetch={prefetch}
      className={classNames}
      onClick={(e) => {
        trackPageViewStart()
        startTransition(() => {
          startRouterTransition()
          if (trackingId) {
            trackClickById()
          }
          if (onClick) {
            onClick(e)
          }
          router.push(href)
        })
      }}
      href={href}
      id={trackingId}
      {...props}
    />
  )
}
