"use client" import { usePathname, useSearchParams } from "next/navigation" import { useCallback, useEffect } from "react" import { useIntl } from "react-intl" import { toast } from "@scandic-hotels/design-system/Toast" import { trackNoAvailability } from "@scandic-hotels/tracking/NoAvailabilityTracking" import { SEARCH_TYPE_REDEMPTION } from "@scandic-hotels/trpc/constants/booking" import { BookingErrorCodeEnum } from "@scandic-hotels/trpc/enums/bookingErrorCode" import useLang from "../../hooks/useLang" import { mapPackageToLabel } from "../../utils/getRoomFeatureDescription" import type { SelectRateBooking } from "../../types/components/selectRate/selectRate" type AvailabilityErrorProps = { booking: SelectRateBooking hotelName: string } export default function AvailabilityError({ booking, hotelName, }: AvailabilityErrorProps) { const intl = useIntl() const pathname = usePathname() const searchParams = useSearchParams() const lang = useLang() const { rooms, fromDate, toDate, hotelId, bookingCode, searchType } = booking const errorCode = searchParams.get("errorCode") const hasAvailabilityError = errorCode === BookingErrorCodeEnum.AvailabilityError const errorMessage = intl.formatMessage({ id: "error.availabilityErrorMessage", defaultMessage: "Unfortunately, one of the rooms you selected is sold out. Please choose another room to proceed.", }) const noAvailabilityTracking = useCallback(() => { const specialRoomType = rooms ?.map((room) => { const packages = room.packages ?.map((pkg) => { mapPackageToLabel(pkg) }) .join(",") return packages ?? "" }) .join("|") trackNoAvailability({ specialRoomType, searchTerm: hotelName, lang, fromDate, toDate, noOfRooms: rooms.length, searchType: "hotel", hotelId, rewardNight: searchType === SEARCH_TYPE_REDEMPTION ? "yes" : "no", bookingCode, pageId: "select-rate", pageName: "hotelreservation|select-rate", pageType: "bookingroomsandratespage", siteSections: "hotelreservation|select-rate", domain: typeof window !== "undefined" ? window.location.host : "", }) }, [ rooms, hotelName, lang, fromDate, toDate, searchType, hotelId, bookingCode, ]) useEffect(() => { if (hasAvailabilityError) { toast.error(errorMessage) noAvailabilityTracking() const newParams = new URLSearchParams(searchParams.toString()) newParams.delete("errorCode") window.history.replaceState({}, "", `${pathname}?${newParams.toString()}`) } }, [ errorMessage, hasAvailabilityError, noAvailabilityTracking, pathname, searchParams, ]) return null }