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

import { AlertTypeEnum } from "@scandic-hotels/common/constants/alert"
import { RateEnum } from "@scandic-hotels/common/constants/rate"
import { Alert } from "@scandic-hotels/design-system/Alert"
import TermModal from "@scandic-hotels/design-system/TermModal"

import { useSelectRateContext } from "../../../../contexts/SelectRate/SelectRateContext"
import { useRateTitles } from "../Rooms/RoomsList/RoomListItem/Rates/useRateTitles"

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

import type { RouterOutput } from "@scandic-hotels/trpc/client"

type RoomAvailability = Extract<
  RouterOutput["hotel"]["availability"]["selectRate"]["rooms"][0],
  { roomConfigurations: unknown }
>

export default function ExtraCostAlert() {
  const intl = useIntl()

  const { availability, input: rooms } = useSelectRateContext()
  const rateTitles = useRateTitles()

  if (!availability.data) {
    return null
  }

  const availableRooms = availability.data.filter(
    (room): room is RoomAvailability => !("error" in room)
  )

  if (availableRooms.length === 0) {
    return null
  }

  const hasMoreThanTwoAdults = rooms.data?.booking.rooms.some(
    (room) => room.adults > 2
  )

  const isRewardNightOrVoucher = availableRooms.some((room) => {
    return room.roomConfigurations.some((config) =>
      config.products?.some((product) =>
        Array.isArray(product)
          ? product.some((p) => "redemption" in p)
          : "voucher" in product
      )
    )
  })

  const rateDefinition = availableRooms.find(
    (room) => room.rateDefinitions.length
  )?.rateDefinitions[0]

  const rateTermDetails = [
    {
      title: rateDefinition?.title ?? "",
      terms: rateDefinition?.generalTerms ?? [],
    },
  ]

  if (!(isRewardNightOrVoucher && hasMoreThanTwoAdults && rateDefinition)) {
    return null
  }

  return (
    <div className={styles.alert}>
      <Alert
        type={AlertTypeEnum.Info}
        heading={intl.formatMessage({
          id: "booking.alert.extraguests",
          defaultMessage: "Extra guest(s)",
        })}
        text={intl.formatMessage({
          id: "booking.alert.extraBeds.text",
          defaultMessage:
            "When booking for more than 2 guests, an additional fee will apply per person, see link for details.",
        })}
        slot={
          <TermModal
            rateTitle={rateTitles[RateEnum.flex].title}
            paymentTerm={rateTitles[RateEnum.flex].paymentTerm}
            rateTermDetails={rateTermDetails}
            variant="text"
          />
        }
      />
    </div>
  )
}
