import { Lang } from "@/constants/languages"
import { dt } from "@/lib/dt"
import {
  getHotelData,
  getPackages,
  getProfileSafely,
  getRoomAvailability,
} from "@/lib/trpc/memoizedRequests"

import { safeTry } from "@/utils/safeTry"

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

import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter"
import { Child } from "@/types/components/hotelReservation/selectRate/selectRate"

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

export async function RoomsContainer({
  hotelId,
  fromDate,
  toDate,
  adultCount,
  childArray,
  lang,
}: Props) {
  const user = await getProfileSafely()

  const fromDateString = dt(fromDate).format("YYYY-MM-DD")
  const toDateString = dt(toDate).format("YYYY-MM-DD")

  const hotelDataPromise = safeTry(
    getHotelData({ hotelId: hotelId.toString(), language: lang })
  )

  const packagesPromise = safeTry(
    getPackages({
      hotelId: hotelId.toString(),
      startDate: fromDateString,
      endDate: toDateString,
      adults: adultCount,
      children: childArray.length > 0 ? childArray.length : undefined,
      packageCodes: [
        RoomPackageCodeEnum.ACCESSIBILITY_ROOM,
        RoomPackageCodeEnum.PET_ROOM,
        RoomPackageCodeEnum.ALLERGY_ROOM,
      ],
    })
  )

  const roomsAvailabilityPromise = safeTry(
    getRoomAvailability({
      hotelId: hotelId,
      roomStayStartDate: fromDateString,
      roomStayEndDate: toDateString,
      adults: adultCount,
      children:
        childArray.length > 0 ? generateChildrenString(childArray) : undefined,
    })
  )

  const [hotelData, hotelDataError] = await hotelDataPromise
  const [packages, packagesError] = await packagesPromise
  const [roomsAvailability, roomsAvailabilityError] =
    await roomsAvailabilityPromise

  if (packagesError) {
    console.error("packagesError", packagesError)

    return (
      <div>Unable to get packages. {JSON.stringify({ ...packagesError })}</div>
    )
  }

  if (roomsAvailabilityError || !roomsAvailability) {
    console.error("roomsAvailabilityError", roomsAvailabilityError)
    return <div>Unable to get room availability</div>
  }

  return (
    <Rooms
      user={user}
      availablePackages={packages ?? []}
      roomsAvailability={roomsAvailability}
      roomCategories={hotelData?.included ?? []}
    />
  )
}
