'use client'

import { login } from '@scandic-hotels/common/constants/routes/handleAuth'

import type { Lang } from '@scandic-hotels/common/constants/language'
import ButtonLink, { ButtonLinkProps } from '../ButtonLink'

interface LoginButtonProps
  extends React.PropsWithChildren<Omit<ButtonLinkProps, 'href'>> {
  lang: Lang
  redirectTo: string | null
  loginPosition: string
}

export function LoginButton({
  lang,
  redirectTo,
  loginPosition,
  ...props
}: LoginButtonProps) {
  let href = login[lang]

  if (redirectTo) {
    const [pathname, existingQuery] = redirectTo.split('?')
    const searchParams = new URLSearchParams(existingQuery)

    searchParams.set('loginPosition', loginPosition)
    const redirectUrl = `${pathname}?${searchParams.toString()}`

    href = `${href}?redirectTo=${encodeURIComponent(redirectUrl)}`
  }

  return <ButtonLink href={href} prefetch={false} {...props} />
}
