"use client"

import NextLink from "next/link"
import { usePathname } from "next/navigation"
import { useMemo } from "react"

import Button from "@/components/TempDesignSystem/Button"
import { trackClick } from "@/utils/tracking"

import type { ButtonLinkProps } from "@/types/components/buttonLink"

export default function ButtonLink({
  children,
  href,
  target,
  trackingId,
  trackingParams,
  onClick = () => {},
  appendToCurrentPath,
  ...buttonProps
}: ButtonLinkProps) {
  const currentPageSlug = usePathname()

  const fullUrl = useMemo(() => {
    let newPath = href
    if (appendToCurrentPath) {
      newPath = `${currentPageSlug}${newPath}`
    }

    return newPath
  }, [href, appendToCurrentPath, currentPageSlug])

  return (
    <Button {...buttonProps} asChild>
      <NextLink
        href={fullUrl}
        target={target}
        onClick={(e) => {
          onClick(e)
          if (trackingId) {
            trackClick(trackingId, trackingParams)
          }
        }}
      >
        {children}
      </NextLink>
    </Button>
  )
}
