import { differenceInCalendarDays, format, isWeekend } from "date-fns"
import { notFound } from "next/navigation"

import { Lang } from "@/constants/languages"
import { selectHotelMap } from "@/constants/routes/hotelReservation"
import { getLocations } from "@/lib/trpc/memoizedRequests"

import {
  fetchAvailableHotels,
  generateChildrenString,
  getFiltersFromHotels,
} from "@/app/[lang]/(live)/(public)/hotelreservation/(standard)/select-hotel/utils"
import HotelCardListing from "@/components/HotelReservation/HotelCardListing"
import HotelFilter from "@/components/HotelReservation/SelectHotel/HotelFilter"
import getHotelReservationQueryParams from "@/components/HotelReservation/SelectRate/RoomSelection/utils"
import { ChevronRightIcon } from "@/components/Icons"
import StaticMap from "@/components/Maps/StaticMap"
import Link from "@/components/TempDesignSystem/Link"
import TrackingSDK from "@/components/TrackingSDK"
import { getIntl } from "@/i18n"
import { setLang } from "@/i18n/serverContext"

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

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

export default async function SelectHotelPage({
  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 intl = await getIntl()
  const selectHotelParams = new URLSearchParams(searchParams)
  const selectHotelParamsObject =
    getHotelReservationQueryParams(selectHotelParams)
  const adults = selectHotelParamsObject.room[0].adults // TODO: Handle multiple rooms
  const child = selectHotelParamsObject.room[0].child
  const children = child ? generateChildrenString(child) : undefined // TODO: Handle multiple rooms

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

  const arrivalDate = new Date(searchParams.fromDate)
  const departureDate = new Date(searchParams.toDate)

  const filterList = getFiltersFromHotels(hotels)

  const pageTrackingData: TrackingSDKPageData = {
    pageId: "select-hotel",
    domainLanguage: params.lang as Lang,
    channel: TrackingChannelEnum["hotelreservation"],
    pageName: "hotelreservation|select-hotel",
    siteSections: "hotelreservation|select-hotel",
    pageType: "bookinghotelspage",
  }

  const hotelsTrackingData: TrackingSDKHotelInfo = {
    availableResults: hotels.length,
    searchTerm: searchParams.city,
    arrivalDate: format(arrivalDate, "yyyy-MM-dd"),
    departureDate: format(departureDate, "yyyy-MM-dd"),
    noOfAdults: adults,
    noOfChildren: child?.length,
    noOfRooms: 1, // // TODO: Handle multiple rooms
    duration: differenceInCalendarDays(departureDate, arrivalDate),
    leadTime: differenceInCalendarDays(arrivalDate, new Date()),
    searchType: "destination",
    bookingTypeofDay: isWeekend(arrivalDate) ? "weekend" : "weekday",
    country: hotels[0].hotelData.address.country,
    region: hotels[0].hotelData.address.city,
  }

  return (
    <main className={styles.main}>
      <section className={styles.section}>
        <Link href={selectHotelMap[params.lang]} keepSearchParams>
          <StaticMap
            city={searchParams.city}
            width={340}
            height={180}
            zoomLevel={11}
            mapType="roadmap"
            altText={`Map of ${searchParams.city} city center`}
          />
        </Link>
        <Link
          className={styles.link}
          color="burgundy"
          href={selectHotelMap[params.lang]}
          keepSearchParams
        >
          {intl.formatMessage({ id: "Show map" })}
          <ChevronRightIcon color="burgundy" />
        </Link>
        <HotelFilter filters={filterList} />
      </section>
      <HotelCardListing hotelData={hotels} />
      <TrackingSDK pageData={pageTrackingData} hotelInfo={hotelsTrackingData} />
    </main>
  )
}
