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

import { Lang } from "@/constants/languages"
import { getHotelData, getLocations } 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 { getHotelReservationQueryParams } from "@/components/HotelReservation/SelectRate/RoomSelection/utils"
import TrackingSDK from "@/components/TrackingSDK"
import { setLang } from "@/i18n/serverContext"
import { safeTry } from "@/utils/safeTry"

import { getValidDates } from "./getValidDates"

import { ChildBedMapEnum } from "@/types/components/bookingWidget/enums"
import type { SelectRateSearchParams } from "@/types/components/hotelReservation/selectRate/selectRate"
import {
  TrackingChannelEnum,
  TrackingSDKHotelInfo,
  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 locations = await getLocations()
  if (!locations || "error" in locations) {
    return null
  }
  const hotel = locations.data.find(
    (location) =>
      "operaId" in location && location.operaId == searchParams.hotel
  )
  if (!hotel) {
    return notFound()
  }
  const selectRoomParams = new URLSearchParams(searchParams)
  const selectRoomParamsObject =
    getHotelReservationQueryParams(selectRoomParams)

  if (!selectRoomParamsObject.room) {
    return notFound()
  }

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

  const adults = selectRoomParamsObject.room[0].adults || 1 // TODO: Handle multiple rooms
  const children = selectRoomParamsObject.room[0].child // TODO: Handle multiple rooms

  const [hotelData, hotelDataError] = await safeTry(
    getHotelData({ hotelId: searchParams.hotel, language: params.lang })
  )

  if (!hotelData && !hotelDataError) {
    return notFound()
  }
  const arrivalDate = new Date(searchParams.fromDate)
  const departureDate = new Date(searchParams.toDate)
  const hotelAttributes = hotelData?.data.attributes

  const roomCategories = hotelData?.included

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

  const hotelsTrackingData: TrackingSDKHotelInfo = {
    searchTerm: searchParams.city ?? hotelAttributes?.name,
    arrivalDate: format(arrivalDate, "yyyy-MM-dd"),
    departureDate: format(departureDate, "yyyy-MM-dd"),
    noOfAdults: adults,
    noOfChildren: children?.length,
    ageOfChildren: children?.map((c) => c.age).join(","),
    childBedPreference: children?.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: hotelAttributes?.address.country,
    hotelID: hotelAttributes?.operaId,
    region: hotelAttributes?.address.city,
    availableResults: roomCategories?.length,
    //lowestRoomPrice:
  }

  const hotelId = +searchParams.hotel

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

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