import { notFound } from "next/navigation"

import { logger } from "@scandic-hotels/common/logger"
import { SEARCH_TYPE_REDEMPTION } from "@scandic-hotels/trpc/constants/booking"

import { BookingFlowConfig } from "../bookingFlowConfig/bookingFlowConfig"
import { SelectRate } from "../components/SelectRate"
import { SelectRateTracking } from "../components/SelectRate/Tracking/SelectRateTracking"
import { SelectRateProvider } from "../contexts/SelectRate/SelectRateContext"
import { getHotel } from "../trpc/memoizedRequests"
import { parseSelectRateSearchParams } from "../utils/url"

import type { Lang } from "@scandic-hotels/common/constants/language"

import type { NextSearchParams } from "../types"

export { SelectRateSkeleton as SelectRatePageSkeleton } from "../components/SelectRate"

export async function SelectRatePage({
  lang,
  searchParams,
  config,
}: {
  lang: Lang
  searchParams: NextSearchParams
  config: BookingFlowConfig
}) {
  const booking = parseSelectRateSearchParams(searchParams)

  if (!booking) {
    logger.debug("Invalid search params", searchParams)
    notFound()
  }
  const isMultiRoom = booking.rooms.length > 1
  const isRedemption = booking.searchType === SEARCH_TYPE_REDEMPTION
  const voucherPattern = /^VO[0-9a-z]*$/i
  const isVoucher = booking.bookingCode
    ? voucherPattern.test(booking.bookingCode)
    : false

  if ((isMultiRoom && isRedemption) || (isMultiRoom && isVoucher)) {
    logger.debug(
      "Invalid search params, can't have multiroom and redemption/voucher",
      { isMultiRoom, isRedemption, isVoucher }
    )
    notFound()
  }

  // If someone tries to update the url with
  // a bookingCode also, then we need to remove it
  if (isRedemption && searchParams.bookingCode) {
    delete searchParams.bookingCode
  }

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

  if (!hotelData) {
    logger.debug("Unable to find hotel data")
    notFound()
  }

  return (
    <BookingFlowConfig config={config}>
      <SelectRateProvider hotelData={hotelData}>
        <SelectRate hotelData={hotelData} booking={booking} />
        <SelectRateTracking hotelData={hotelData} booking={booking} />
      </SelectRateProvider>
    </BookingFlowConfig>
  )
}
