import { notFound } from "next/navigation"

import { env } from "@/env/server"
import { getCityCoordinates, 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 { MapContainer } from "@/components/MapContainer"
import { setLang } from "@/i18n/serverContext"

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

import type { HotelData } from "@/types/components/hotelReservation/selectHotel/hotelCardListingProps"
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 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 validHotels = hotels.filter(
    (hotel): hotel is HotelData => hotel !== null
  )

  const hotelPins = getHotelPins(validHotels)
  const filterList = getFiltersFromHotels(validHotels)
  const cityCoordinates = await getCityCoordinates({
    city: city.name,
    hotel: { address: hotels?.[0]?.hotelData?.address.streetAddress },
  })

  return (
    <MapContainer>
      <SelectHotelMap
        apiKey={googleMapsApiKey}
        hotelPins={hotelPins}
        mapId={googleMapId}
        hotels={validHotels}
        filterList={filterList}
        cityCoordinates={cityCoordinates}
      />
    </MapContainer>
  )
}
