import { notFound } from "next/navigation"

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

import {
  fetchAvailableHotels,
  generateChildrenString,
  getFiltersFromHotels,
  getPointOfInterests,
} from "@/app/[lang]/(live)/(public)/hotelreservation/(standard)/select-hotel/utils"
import SelectHotelMap from "@/components/HotelReservation/SelectHotel/SelectHotelMap"
import getHotelReservationQueryParams from "@/components/HotelReservation/SelectRate/RoomSelection/utils"
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>) {
  const googleMapId = env.GOOGLE_DYNAMIC_MAP_ID
  const googleMapsApiKey = env.GOOGLE_STATIC_MAP_KEY
  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 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 filters = getFiltersFromHotels(hotels)

  const pointOfInterests = getPointOfInterests(hotels)

  return (
    <main className={styles.main}>
      <SelectHotelMap
        apiKey={googleMapsApiKey}
        // TODO: use correct coordinates. The city center?
        coordinates={{ lat: 59.32, lng: 18.01 }}
        pointsOfInterest={pointOfInterests}
        mapId={googleMapId}
      />
    </main>
  )
}
