import { notFound } from "next/navigation"

import { getProfileSafely } from "@/lib/trpc/memoizedRequests"
import { serverClient } from "@/lib/trpc/server"

import HotelInfoCard from "@/components/HotelReservation/SelectRate/HotelInfoCard"
import Rooms from "@/components/HotelReservation/SelectRate/Rooms"
import getHotelReservationQueryParams from "@/components/HotelReservation/SelectRate/RoomSelection/utils"
import { setLang } from "@/i18n/serverContext"

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

export default async function SelectRatePage({
  params,
  searchParams,
}: PageArgs<LangParams & { section: string }, SelectRateSearchParams>) {
  setLang(params.lang)

  const selectRoomParams = new URLSearchParams(searchParams)
  const selectRoomParamsObject =
    getHotelReservationQueryParams(selectRoomParams)

  if (!selectRoomParamsObject.room) {
    return notFound()
  }

  const adults = selectRoomParamsObject.room[0].adults // TODO: Handle multiple rooms
  const children = selectRoomParamsObject.room[0].child?.length // TODO: Handle multiple rooms

  const [hotelData, roomsAvailability, packages, user] = await Promise.all([
    serverClient().hotel.hotelData.get({
      hotelId: searchParams.hotel,
      language: params.lang,
      include: ["RoomCategories"],
    }),
    serverClient().hotel.availability.rooms({
      hotelId: parseInt(searchParams.hotel, 10),
      roomStayStartDate: searchParams.fromDate,
      roomStayEndDate: searchParams.toDate,
      adults,
      children,
    }),
    serverClient().hotel.packages.get({
      hotelId: searchParams.hotel,
      startDate: searchParams.fromDate,
      endDate: searchParams.toDate,
      adults: adults,
      children: children,
      packageCodes: [
        RoomPackageCodeEnum.ACCESSIBILITY_ROOM,
        RoomPackageCodeEnum.PET_ROOM,
        RoomPackageCodeEnum.ALLERGY_ROOM,
      ],
    }),
    getProfileSafely(),
  ])

  if (!roomsAvailability) {
    return "No rooms found" // TODO: Add a proper error message
  }

  if (!hotelData) {
    return "No hotel data found" // TODO: Add a proper error message
  }

  const roomCategories = hotelData?.included

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