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

import { Lang } from "@/constants/languages"
import { dt } from "@/lib/dt"
import {
  getHotelData,
  getLocations,
  getProfileSafely,
} from "@/lib/trpc/memoizedRequests"
import { serverClient } from "@/lib/trpc/server"

import HotelInfoCard from "@/components/HotelReservation/SelectRate/HotelInfoCard"
import Rooms from "@/components/HotelReservation/SelectRate/Rooms"
import {
  generateChildrenString,
  getHotelReservationQueryParams,
} from "@/components/HotelReservation/SelectRate/RoomSelection/utils"
import TrackingSDK from "@/components/TrackingSDK"
import { setLang } from "@/i18n/serverContext"

import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter"
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 validFromDate =
    searchParams.fromDate &&
    dt(searchParams.fromDate).isAfter(dt().subtract(1, "day"))
      ? searchParams.fromDate
      : dt().utc().format("YYYY-MM-DD")
  const validToDate =
    searchParams.toDate && dt(searchParams.toDate).isAfter(validFromDate)
      ? searchParams.toDate
      : dt().utc().add(1, "day").format("YYYY-MM-DD")
  const adults = selectRoomParamsObject.room[0].adults || 1 // TODO: Handle multiple rooms
  const childrenCount = selectRoomParamsObject.room[0].child?.length
  const children = selectRoomParamsObject.room[0].child
    ? generateChildrenString(selectRoomParamsObject.room[0].child)
    : undefined // TODO: Handle multiple rooms

  const [hotelData, roomsAvailability, packages, user] = await Promise.all([
    getHotelData({ hotelId: searchParams.hotel, language: params.lang }),
    serverClient().hotel.availability.rooms({
      hotelId: parseInt(searchParams.hotel, 10),
      roomStayStartDate: validFromDate,
      roomStayEndDate: validToDate,
      adults,
      children,
    }),
    serverClient().hotel.packages.get({
      hotelId: searchParams.hotel,
      startDate: searchParams.fromDate,
      endDate: searchParams.toDate,
      adults,
      children: childrenCount,
      packageCodes: [
        RoomPackageCodeEnum.ACCESSIBILITY_ROOM,
        RoomPackageCodeEnum.PET_ROOM,
        RoomPackageCodeEnum.ALLERGY_ROOM,
      ],
    }),
    getProfileSafely(),
  ])

  const arrivalDate = new Date(searchParams.fromDate)
  const departureDate = new Date(searchParams.toDate)
  const hotelAttributes = hotelData?.data.attributes

  const roomCategories = hotelData?.included

  const noRoomsAvailable = roomsAvailability?.roomConfigurations.reduce(
    (acc, room) => {
      return acc && room.status === "NotAvailable"
    },
    true
  )

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

  const hotelsTrackingData: TrackingSDKHotelInfo = {
    searchTerm: searchParams.city,
    arrivalDate: format(arrivalDate, "yyyy-MM-dd"),
    departureDate: format(departureDate, "yyyy-MM-dd"),
    noOfAdults: adults,
    noOfChildren: childrenCount,
    //childBedPreference // "adults|adults|extra|adults"
    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,
    region: hotelAttributes?.address.city,
    availableResults: roomCategories?.length,
    //lowestRoomPrice:
  }

  if (!roomsAvailability) {
    return "No rooms found" // TODO: Add a proper error message
  }

  if (!hotelData) {
    return "No hotel data found" // TODO: Add a proper error message
  }

  return (
    <>
      <HotelInfoCard
        hotelData={hotelData}
        noAvailability={!!noRoomsAvailable}
      />
      <Rooms
        roomsAvailability={roomsAvailability}
        roomCategories={roomCategories ?? []}
        user={user}
        availablePackages={packages ?? []}
      />
      <TrackingSDK pageData={pageTrackingData} hotelInfo={hotelsTrackingData} />
    </>
  )
}
