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

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

import HotelInfoCard from "@/components/HotelReservation/SelectRate/HotelInfoCard"
import { RoomsContainer } from "@/components/HotelReservation/SelectRate/Rooms/RoomsContainer"
import { RoomsContainerSkeleton } from "@/components/HotelReservation/SelectRate/Rooms/RoomsContainerSkeleton"
import TrackingSDK from "@/components/TrackingSDK"
import { setLang } from "@/i18n/serverContext"

import { getHotelSearchDetails } from "../utils"
import { getValidDates } from "./getValidDates"

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 } =
    searchDetails

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

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

  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,
    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

  return (
    <>
      <HotelInfoCard
        hotelId={hotelId}
        lang={params.lang}
        fromDate={fromDate.toDate()}
        toDate={toDate.toDate()}
        adultCount={adultsInRoom}
        childArray={childrenInRoom}
      />

      <Suspense key={hotelId} fallback={<RoomsContainerSkeleton />}>
        <RoomsContainer
          hotelId={hotelId}
          lang={params.lang}
          fromDate={fromDate.toDate()}
          toDate={toDate.toDate()}
          adultCount={adultsInRoom}
          childArray={childrenInRoom}
        />
      </Suspense>
      <Suspense fallback={null}>
        <TrackingSDK
          pageData={pageTrackingData}
          hotelInfo={hotelsTrackingData}
        />
      </Suspense>
    </>
  )
}
