import { notFound } from "next/navigation"
import { Suspense } from "react"

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

import { SelectHotelMapContainer } from "@/components/HotelReservation/SelectHotel/SelectHotelMap/SelectHotelMapContainer"
import { SelectHotelMapContainerSkeleton } from "@/components/HotelReservation/SelectHotel/SelectHotelMap/SelectHotelMapContainerSkeleton"
import {
  generateChildrenString,
  getHotelReservationQueryParams,
} from "@/components/HotelReservation/SelectRate/RoomSelection/utils"
import { MapContainer } from "@/components/MapContainer"
import { setLang } from "@/i18n/serverContext"

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

import type { SelectHotelSearchParams } from "@/types/components/hotelReservation/selectHotel/selectHotelSearchParams"
import type { LangParams, PageArgs } from "@/types/params"

export default async function SelectHotelMapPage({
  params,
  searchParams,
}: PageArgs<LangParams, SelectHotelSearchParams>) {
  setLang(params.lang)
  const locations = await getLocations()

  if (!locations || "error" in locations) {
    return null
  }
  const city = locations.data.find(
    (location) =>
      location.name.toLowerCase() === searchParams.city.toLowerCase()
  )
  if (!city) return notFound()

  const selectHotelParams = new URLSearchParams(searchParams)
  const selectHotelParamsObject =
    getHotelReservationQueryParams(selectHotelParams)
  const adultsInRoom = selectHotelParamsObject.room[0].adults // TODO: Handle multiple rooms
  const childrenInRoom = selectHotelParamsObject.room[0].child
    ? generateChildrenString(selectHotelParamsObject.room[0].child)
    : undefined // TODO: Handle multiple rooms

  return (
    <div className={styles.main}>
      <MapContainer>
        <Suspense key={city.id} fallback={<SelectHotelMapContainerSkeleton />}>
          <SelectHotelMapContainer
            city={city}
            searchParams={searchParams}
            adultsInRoom={adultsInRoom}
            childrenInRoom={childrenInRoom}
          />
        </Suspense>
      </MapContainer>
    </div>
  )
}
