import { dt } from "@/lib/dt"
import { getRoomsAvailability } from "@/lib/trpc/memoizedRequests"

import Alert from "@/components/TempDesignSystem/Alert"
import { getIntl } from "@/i18n"
import { safeTry } from "@/utils/safeTry"

import { generateChildrenString } from "../RoomSelection/utils"

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

import type { Child } from "@/types/components/hotelReservation/selectRate/selectRate"
import { AlertTypeEnum } from "@/types/enums/alert"
import type { Lang } from "@/constants/languages"

type Props = {
  hotelId: number
  lang: Lang
  adultCount: number
  childArray?: Child[]
  fromDate: Date
  toDate: Date
}

export async function NoRoomsAlert({
  hotelId,
  fromDate,
  toDate,
  childArray,
  adultCount,
  lang,
}: Props) {
  const [availability, availabilityError] = await safeTry(
    getRoomsAvailability({
      hotelId: hotelId,
      roomStayStartDate: dt(fromDate).format("YYYY-MM-DD"),
      roomStayEndDate: dt(toDate).format("YYYY-MM-DD"),
      adults: adultCount,
      children: childArray ? generateChildrenString(childArray) : undefined, // TODO: Handle multiple rooms,
    })
  )

  if (!availability || availabilityError) {
    return null
  }

  const noRoomsAvailable = availability.roomConfigurations.reduce(
    (acc, room) => {
      return acc && room.status === "NotAvailable"
    },
    true
  )

  if (!noRoomsAvailable) {
    return null
  }

  const intl = await getIntl(lang)
  return (
    <div className={styles.hotelAlert}>
      <Alert
        type={AlertTypeEnum.Info}
        text={intl.formatMessage({
          id: "There are no rooms available that match your request",
        })}
      />
    </div>
  )
}
