import {
  getHotelData,
  getProfileSafely,
  getRoomAvailability,
} from "@/lib/trpc/memoizedRequests"
import { HotelIncludeEnum } from "@/server/routers/hotels/input"

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

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

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

  const user = await getProfileSafely()
  const hotelData = await getHotelData(hotel, params.lang, undefined, [HotelIncludeEnum.RoomCategories])
  const availability = await getRoomAvailability({
    hotelId: parseInt(hotel),
    adults,
    children,
    roomStayStartDate: fromDate,
    roomStayEndDate: toDate,
  })

  if (!hotelData?.data || !hotelData?.included || !availability) {
    console.error("No hotel or availability data", hotelData, availability)

    // TODO: handle this case
    return null
  }

  const chosenRoom = availability.roomConfigurations.find(
    (availRoom) => availRoom.roomTypeCode === roomTypeCode
  )

  if (!chosenRoom) {
    // TODO: handle this case
    console.error("No chosen room", chosenRoom)
    return null
  }

  const cancellationText =
    availability?.rateDefinitions.find((rate) => rate.rateCode === rateCode)
      ?.cancellationText ?? ""

  const memberPrice =
    chosenRoom.products.find(
      (rate) => rate.productType.member?.rateCode === rateCode
    )?.productType.member?.localPrice.pricePerStay ?? "0"

  const publicPrice =
    chosenRoom.products.find(
      (rate) => rate.productType.public?.rateCode === rateCode
    )?.productType.public?.localPrice.pricePerStay ?? "0"

  const price = user ? memberPrice : publicPrice

  return (
    <Summary
      isMember={!!user}
      room={{
        roomType: chosenRoom.roomType,
        price: formatNumber(parseInt(price)),
        adults,
        cancellationText,
      }}
    />
  )
}
