"use client"
import NextLink from "next/link"
import { usePathname, useSearchParams } from "next/navigation"
import { useCallback, useMemo } from "react"

import { trackClick } 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,
  /**
   * Decides if the link should include the current search params in the URL
   */
  keepSearchParams,
  ...props
}: LinkProps) {
  const currentPageSlug = usePathname()
  const searchParams = useSearchParams()
  let isActive = active || currentPageSlug === href

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

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

  const fullUrl = useMemo(() => {
    const search =
      keepSearchParams && searchParams.size ? `?${searchParams}` : ""
    return `${href}${search}`
  }, [href, searchParams, keepSearchParams])

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

  return (
    <NextLink
      scroll={scroll}
      prefetch={prefetch}
      className={classNames}
      onClick={(e) => {
        if (onClick) {
          onClick(e)
        }
        if (trackingId) {
          trackClickById()
        }
      }}
      href={fullUrl}
      id={trackingId}
      {...props}
    />
  )
}
