import {
  getProfileSafely,
  getSelectedRoomAvailability,
} from "@/lib/trpc/memoizedRequests"

import Summary from "@/components/HotelReservation/EnterDetails/Summary"
import { getQueryParamsForEnterDetails } from "@/components/HotelReservation/SelectRate/RoomSelection/utils"

import { SelectRateSearchParams } from "@/types/components/hotelReservation/selectRate/selectRate"
import { LangParams, PageArgs, SearchParams } from "@/types/params"

export default async function SummaryPage({
  searchParams,
}: PageArgs<LangParams, SearchParams<SelectRateSearchParams>>) {
  const selectRoomParams = new URLSearchParams(searchParams)
  const { hotel, adults, children, roomTypeCode, rateCode, fromDate, toDate } =
    getQueryParamsForEnterDetails(selectRoomParams)

  const availability = await getSelectedRoomAvailability({
    hotelId: hotel,
    adults,
    children,
    roomStayStartDate: fromDate,
    roomStayEndDate: toDate,
    rateCode,
    roomTypeCode,
  })
  const user = await getProfileSafely()

  if (!availability) {
    console.error("No hotel or availability data", availability)
    // TODO: handle this case
    return null
  }

  const prices = user
    ? {
        local: {
          price: availability.memberRate?.localPrice.pricePerStay,
          currency: availability.memberRate?.localPrice.currency,
        },
        euro: {
          price: availability.memberRate?.requestedPrice?.pricePerStay,
          currency: availability.memberRate?.requestedPrice?.currency,
        },
      }
    : {
        local: {
          price: availability.publicRate?.localPrice.pricePerStay,
          currency: availability.publicRate?.localPrice.currency,
        },
        euro: {
          price: availability.publicRate?.requestedPrice?.pricePerStay,
          currency: availability.publicRate?.requestedPrice?.currency,
        },
      }

  return (
    <Summary
      isMember={!!user}
      room={{
        roomType: availability.selectedRoom.roomType,
        localPrice: prices.local,
        euroPrice: prices.euro,
        adults,
        cancellationText: availability.cancellationText,
      }}
    />
  )
}
