import { differenceInCalendarDays, format, isWeekend } from "date-fns"
import stringify from "json-stable-stringify-without-jsonify"
import { notFound } from "next/navigation"
import { Suspense } from "react"

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

import { getValidDates } from "@/app/[lang]/(live)/(public)/hotelreservation/(standard)/select-rate/getValidDates"
import { getHotelSearchDetails } from "@/app/[lang]/(live)/(public)/hotelreservation/(standard)/utils"
import HotelInfoCard, {
  HotelInfoCardSkeleton,
} from "@/components/HotelReservation/SelectRate/HotelInfoCard"
import { RoomsContainer } from "@/components/HotelReservation/SelectRate/RoomsContainer"
import TrackingSDK from "@/components/TrackingSDK"
import { setLang } from "@/i18n/serverContext"
import { convertSearchParamsToObj } from "@/utils/url"

import { ChildBedMapEnum } from "@/types/components/bookingWidget/enums"
import type { SelectRateSearchParams } from "@/types/components/hotelReservation/selectRate/selectRate"
import {
  TrackingChannelEnum,
  type TrackingSDKHotelInfo,
  type TrackingSDKPageData,
} from "@/types/components/tracking"
import type { LangParams, PageArgs } from "@/types/params"

export default async function SelectRatePage({
  params,
  searchParams,
}: PageArgs<LangParams & { section: string }, SelectRateSearchParams>) {
  setLang(params.lang)
  const searchDetails = await getHotelSearchDetails({ searchParams })
  if (!searchDetails?.hotel) {
    return notFound()
  }
  const { hotel, adultsInRoom, childrenInRoom, selectHotelParams, bookingCode } =
    searchDetails

  const { fromDate, toDate } = getValidDates(
    selectHotelParams.fromDate,
    selectHotelParams.toDate
  )

  const hotelData = await getHotel({
    hotelId: hotel.id,
    isCardOnlyPayment: false,
    language: params.lang,
  })

  const arrivalDate = fromDate.toDate()
  const departureDate = toDate.toDate()

  const pageTrackingData: TrackingSDKPageData = {
    pageId: "select-rate",
    domainLanguage: params.lang,
    channel: TrackingChannelEnum["hotelreservation"],
    pageName: "hotelreservation|select-rate",
    siteSections: "hotelreservation|select-rate",
    pageType: "bookingroomsandratespage",
    siteVersion: "new-web",
  }

  const hotelsTrackingData: TrackingSDKHotelInfo = {
    searchTerm: selectHotelParams.city ?? hotel?.name,
    arrivalDate: format(arrivalDate, "yyyy-MM-dd"),
    departureDate: format(departureDate, "yyyy-MM-dd"),
    noOfAdults: adultsInRoom[0], // TODO: Handle multiple rooms
    noOfChildren: childrenInRoom?.length,
    ageOfChildren: childrenInRoom?.map((c) => c.age).join(","),
    childBedPreference: childrenInRoom
      ?.map((c) => ChildBedMapEnum[c.bed])
      .join("|"),
    noOfRooms: 1, // // TODO: Handle multiple rooms
    duration: differenceInCalendarDays(departureDate, arrivalDate),
    leadTime: differenceInCalendarDays(arrivalDate, new Date()),
    searchType: "hotel",
    bookingTypeofDay: isWeekend(arrivalDate) ? "weekend" : "weekday",
    country: hotelData?.hotel.address.country,
    hotelID: hotel?.id,
    region: hotelData?.hotel.address.city,
  }

  const hotelId = +hotel.id

  const booking = convertSearchParamsToObj<SelectRateSearchParams>(searchParams)
  const suspenseKey = stringify(searchParams)

  return (
    <>
      <Suspense fallback={<HotelInfoCardSkeleton />}>
        <HotelInfoCard hotelData={hotelData} />
      </Suspense>

      <RoomsContainer
        hotelData={hotelData}
        adultArray={adultsInRoom}
        booking={booking}
        childArray={childrenInRoom}
        fromDate={arrivalDate}
        hotelId={hotelId}
        toDate={departureDate}
      />

      <Suspense key={`${suspenseKey}-tracking`} fallback={null}>
        <TrackingSDK
          pageData={pageTrackingData}
          hotelInfo={hotelsTrackingData}
        />
      </Suspense>
    </>
  )
}
