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 "../../utils"
import { combineRoomAvailabilities } from "../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
  adultArray: number[]
  childArray?: Child[]
  fromDate: Date
  toDate: Date
}

export async function NoRoomsAlert({
  hotelId,
  fromDate,
  toDate,
  childArray,
  adultArray,
  lang,
}: Props) {
  const fromDateString = dt(fromDate).format("YYYY-MM-DD")
  const toDateString = dt(toDate).format("YYYY-MM-DD")

  const uniqueAdultCounts = [...new Set(adultArray)]
  const roomsAvailabilityPromises = uniqueAdultCounts.map((adultCount) => {
    return safeTry(
      getRoomsAvailability({
        hotelId: hotelId,
        roomStayStartDate: fromDateString,
        roomStayEndDate: toDateString,
        adults: adultCount,
        children:
          childArray && childArray.length > 0
            ? generateChildrenString(childArray)
            : undefined,
      })
    )
  })

  const roomsAvailabilityResults = await Promise.all(roomsAvailabilityPromises)

  const roomsAvailability = combineRoomAvailabilities({
    availabilityResults: roomsAvailabilityResults,
  })

  if (!roomsAvailability) {
    return null
  }

  const noRoomsAvailable = roomsAvailability.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>
  )
}
