import { notFound } from "next/navigation"

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

import { getHotelPins } from "@/components/HotelReservation/HotelCardDialogListing/utils"
import SelectHotelMap from "@/components/HotelReservation/SelectHotel/SelectHotelMap"
import {
  generateChildrenString,
  getHotelReservationQueryParams,
} from "@/components/HotelReservation/SelectRate/RoomSelection/utils"
import { MapModal } from "@/components/MapModal"
import { setLang } from "@/i18n/serverContext"

import { fetchAvailableHotels } from "../../utils"

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>) {
  if (env.HIDE_FOR_NEXT_RELEASE) {
    return notFound()
  }

  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 googleMapId = env.GOOGLE_DYNAMIC_MAP_ID
  const googleMapsApiKey = env.GOOGLE_STATIC_MAP_KEY

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

  const hotels = await fetchAvailableHotels({
    cityId: city.id,
    roomStayStartDate: searchParams.fromDate,
    roomStayEndDate: searchParams.toDate,
    adults,
    children,
  })

  const hotelPins = getHotelPins(hotels)

  return (
    <MapModal>
      <SelectHotelMap
        apiKey={googleMapsApiKey}
        hotelPins={hotelPins}
        mapId={googleMapId}
        hotels={hotels}
      />
    </MapModal>
  )
}
