"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 { 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
}

export default function AvailabilityError({ booking }: 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({
    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: hotelId,
      lang,
      fromDate,
      toDate,
      noOfRooms: rooms.length,
      searchType,
      hotelId,
      bookingCode,
      pageId: "select-rate",
      pageName: "hotelreservation|select-rate",
      pageType: "bookingroomsandratespage",
      siteSections: "hotelreservation|select-rate",
    })
  }, [rooms, hotelId, lang, fromDate, toDate, searchType, 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
}
