import { Suspense } from "react"

import { Typography } from "@scandic-hotels/design-system/Typography"

import { getBookingConfirmation } from "@/lib/trpc/memoizedRequests"

import { getIntl } from "@/i18n"

import MultiRoom from "../MultiRoom"
import MultiRoomSkeleton from "../MultiRoom/MultiRoomSkeleton"
import PriceDetails from "../PriceDetails"
import { SingleRoom } from "../SingleRoom"
import TotalPrice from "./TotalPrice"

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

import { type Hotel, type Room } from "@/types/hotel"
import type { BookingConfirmation } from "@/types/trpc/routers/booking/confirmation"
import type { User } from "@/types/user"

interface RoomsProps {
  booking: BookingConfirmation["booking"]
  room:
    | (Room & {
        bedType: Room["roomTypes"][number]
      })
    | null
  hotel: Hotel
  user: User | null
}

export default async function Rooms({
  booking,
  room,
  hotel,
  user,
}: RoomsProps) {
  const intl = await getIntl()

  if (!room) {
    return null
  }

  const linkedBookingPromises = booking.linkedReservations
    ? booking.linkedReservations.map((linkedBooking) => {
        return getBookingConfirmation(linkedBooking.confirmationNumber)
      })
    : []

  const isMultiRoom = booking.linkedReservations.length > 0

  return (
    <div className={styles.wrapper}>
      {isMultiRoom && (
        <Typography variant="Title/sm">
          <h2 className={styles.title}>
            {intl.formatMessage({ id: "Your rooms" })}
          </h2>
        </Typography>
      )}
      <div className={styles.container}>
        {!isMultiRoom ? (
          <SingleRoom
            bedType={room.bedType}
            image={room.images[0]}
            hotel={hotel}
            user={user}
          />
        ) : (
          <div className={styles.roomsContainer}>
            <MultiRoom booking={booking} room={room} user={user} />
            {booking.linkedReservations.map((linkedRes, index) => (
              <div
                key={linkedRes.confirmationNumber}
                className={styles.roomWrapper}
              >
                <Suspense fallback={<MultiRoomSkeleton />}>
                  <MultiRoom
                    bookingPromise={linkedBookingPromises[index]}
                    index={index}
                    user={user}
                  />
                </Suspense>
              </div>
            ))}
          </div>
        )}
      </div>
      {isMultiRoom && (
        <div className={styles.totalContainer}>
          <div className={styles.total}>
            <Typography variant="Body/Lead text">
              <p>{intl.formatMessage({ id: "Booking total" })}:</p>
            </Typography>
            <TotalPrice variant="Title/Subtitle/lg" />
          </div>

          <PriceDetails />
        </div>
      )}
    </div>
  )
}
