"use client"
import { useIntl } from "react-intl"

import { AlertTypeEnum } from "@scandic-hotels/common/constants/alert"
import { alternativeHotels } from "@scandic-hotels/common/constants/routes/hotelReservation"
import { Alert } from "@scandic-hotels/design-system/Alert"
import { AvailabilityEnum } from "@scandic-hotels/trpc/enums/selectHotel"

import { useSelectRateContext } from "@/contexts/SelectRate/SelectRateContext"
import useLang from "@/hooks/useLang"

import styles from "./alert.module.css"

export default function NoAvailabilityAlert({
  roomIndex,
}: {
  roomIndex: number
}) {
  const lang = useLang()
  const intl = useIntl()

  const { availability, input } = useSelectRateContext()
  if (availability.isFetching || !availability.data) {
    return null
  }

  const indexed = availability.data[roomIndex]
  const hasAvailabilityError = "error" in indexed
  if (hasAvailabilityError) {
    return null
  }

  const noAvailableRooms = hasAvailableRoomsForRoom(indexed.roomConfigurations)

  const alertLink =
    roomIndex !== -1 &&
    (input.data?.booking.rooms.at(roomIndex)?.packages ?? []).length === 0
      ? {
          title: intl.formatMessage({
            defaultMessage: "See alternative hotels",
          }),
          url: `${alternativeHotels(lang)}`,
          keepSearchParams: true,
        }
      : null

  if (noAvailableRooms) {
    const text = intl.formatMessage({
      defaultMessage: "There are no rooms available that match your request.",
    })
    return (
      <div className={styles.hotelAlert}>
        <Alert
          type={AlertTypeEnum.Info}
          heading={intl.formatMessage({
            defaultMessage: "No availability",
          })}
          text={text}
          link={alertLink}
        />
      </div>
    )
  }

  const isPublicPromotionWithCode = indexed.roomConfigurations.some((room) => {
    const filteredCampaigns = room.campaign.filter(Boolean)
    return filteredCampaigns.length
      ? filteredCampaigns.every(
          (product) => !!product.rateDefinition?.isCampaignRate
        )
      : false
  })

  const noAvailableBookingCodeRooms =
    !isPublicPromotionWithCode &&
    indexed.roomConfigurations.every(
      (room) =>
        room.status === AvailabilityEnum.NotAvailable || !room.code.length
    )

  if (input.bookingCode && noAvailableBookingCodeRooms) {
    const bookingCodeText = intl.formatMessage(
      {
        defaultMessage:
          "We found no available rooms using this booking code ({bookingCode}). See available rates below.",
      },
      { bookingCode: input.bookingCode }
    )

    return (
      <div className={styles.hotelAlert}>
        <Alert
          type={AlertTypeEnum.Info}
          heading={intl.formatMessage({
            defaultMessage: "No availability",
          })}
          text={bookingCodeText}
          link={alertLink}
        />
      </div>
    )
  }

  return null
}

function hasAvailableRoomsForRoom(
  roomConfigurations: Extract<
    NonNullable<
      ReturnType<typeof useSelectRateContext>["availability"]["data"]
    >[number],
    { roomConfigurations: unknown }
  >["roomConfigurations"]
) {
  return roomConfigurations.every(
    (roomConfig) => roomConfig.status === AvailabilityEnum.NotAvailable
  )
}
