"use client"

import { useEffect } from "react"
import { useIntl } from "react-intl"

import { myStay } from "@scandic-hotels/common/constants/routes/myStay"
import ButtonLink from "@scandic-hotels/design-system/ButtonLink"
import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"

import useLang from "@/hooks/useLang"

import type { ManageBookingProps } from "@/types/components/hotelReservation/bookingConfirmation/actions/manageBooking"
import type { AdditionalInfoCookieValue } from "@/components/HotelReservation/FindMyBooking/AdditionalInfoForm"

export default function ManageBooking({ booking }: ManageBookingProps) {
  const intl = useIntl()
  const lang = useLang()

  const { refId, confirmationNumber } = booking
  const { email, firstName, lastName } = booking.guest
  useEffect(() => {
    // Setting the `bv` cookie allows direct access to My stay without prompting for more information.
    const value: AdditionalInfoCookieValue = {
      email,
      firstName,
      lastName,
      confirmationNumber,
    }
    document.cookie = `bv=${JSON.stringify(value)}; Path=/; Max-Age=600; Secure; SameSite=Strict`
  }, [confirmationNumber, email, firstName, lastName])

  const myStayURL = `${myStay[lang]}?RefId=${encodeURIComponent(refId)}`

  return (
    <ButtonLink
      href={myStayURL}
      variant="Text"
      size="Small"
      color="Primary"
      typography="Body/Supporting text (caption)/smBold"
      wrapping
    >
      <MaterialIcon size={20} icon="edit_square" color="CurrentColor" />
      {intl.formatMessage({
        defaultMessage: "Manage booking",
      })}
    </ButtonLink>
  )
}
