import { notFound } from "next/navigation"
import { Suspense } from "react"

import { dt } from "@/lib/dt"
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 { setLang } from "@/i18n/serverContext"
import { safeTry } from "@/utils/safeTry"

import type { SelectRateSearchParams } from "@/types/components/hotelReservation/selectRate/selectRate"
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 =
    searchParams.fromDate &&
    dt(searchParams.fromDate).isAfter(dt().subtract(1, "day"))
      ? dt(searchParams.fromDate)
      : dt().utc()
  const toDate =
    searchParams.toDate && dt(searchParams.toDate).isAfter(fromDate)
      ? dt(searchParams.toDate)
      : dt().utc().add(1, "day")

  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 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>
    </>
  )
}
