"use client"

import { type PropsWithChildren, useEffect } from "react"

import { login } from "@/constants/routes/handleAuth"

import Link from "@/components/TempDesignSystem/Link"
import useLang from "@/hooks/useLang"
import { useLazyPathname } from "@/hooks/useLazyPathname"
import { trackLoginClick } from "@/utils/tracking"

import type { TrackingPosition } from "@/types/components/tracking"
import type { LinkProps } from "@/components/TempDesignSystem/Link/link"

export default function LoginButton({
  position,
  trackingId,
  children,
  ...props
}: PropsWithChildren<
  {
    trackingId: string
    position: TrackingPosition
  } & Omit<LinkProps, "href">
>) {
  const lang = useLang()
  const pathName = useLazyPathname({ includeSearchParams: true })

  const href = pathName
    ? `${login[lang]}?redirectTo=${encodeURIComponent(pathName)}`
    : login[lang]

  useEffect(() => {
    function trackLogin() {
      trackLoginClick(position)
    }
    document.getElementById(trackingId)?.addEventListener("click", trackLogin)
    return () => {
      document
        .getElementById(trackingId)
        ?.removeEventListener("click", trackLogin)
    }
  }, [position, trackingId])

  return (
    <Link id={trackingId} prefetch={false} {...props} href={href}>
      {children}
    </Link>
  )
}
