import { redirect } from "next/navigation"

import { selectRate } from "@/constants/routes/hotelReservation"
import {
  getProfileSafely,
  getSelectedRoomAvailability,
} from "@/lib/trpc/memoizedRequests"

import { generateChildrenString } from "@/components/HotelReservation/SelectRate/RoomSelection/utils"
import { getLang } from "@/i18n/serverContext"

import ClientSummary from "./Client"

import type { SummaryPageProps } from "@/types/components/hotelReservation/summary"

export default async function Summary({
  adults,
  fromDate,
  hotelId,
  kids,
  packageCodes,
  rateCode,
  roomTypeCode,
  toDate,
}: SummaryPageProps) {
  const lang = getLang()

  const availability = await getSelectedRoomAvailability({
    adults,
    children: kids ? generateChildrenString(kids) : undefined,
    hotelId,
    packageCodes,
    rateCode,
    roomStayStartDate: fromDate,
    roomStayEndDate: toDate,
    roomTypeCode,
  })
  const user = await getProfileSafely()

  if (!availability || !availability.selectedRoom) {
    console.error("No hotel or availability data", availability)
    // TODO: handle this case
    redirect(selectRate(lang))
  }

  return (
    <ClientSummary
      adults={adults}
      cancellationText={availability.cancellationText}
      isMember={!!user}
      kids={kids}
      memberRate={availability.memberRate}
      rateDetails={availability.rateDetails}
      roomType={availability.selectedRoom.roomType}
    />
  )
}
