"use client"

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

import ButtonLink from "@scandic-hotels/design-system/ButtonLink"
import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"

import { useBookingFlowConfig } from "../../../../bookingFlowConfig/bookingFlowConfigContext"
import useLang from "../../../../hooks/useLang"

import type { BookingConfirmation } from "@scandic-hotels/trpc/types/bookingConfirmation"

import type { AdditionalInfoCookieValue } from "../../../../types/components/findMyBooking/additionalInfoCookieValue"

type ManageBookingProps = Pick<BookingConfirmation, "booking">

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

  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 = `${routes.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>
  )
}
