import { cookies } from "next/headers"
import { notFound, redirect } from "next/navigation"

import { decrypt } from "@scandic-hotels/trpc/utils/encryption"

import { BookingFlowConfig } from "../bookingFlowConfig/bookingFlowConfig"
import { BookingConfirmation } from "../components/BookingConfirmation"
import { getBookingConfirmation } from "../trpc/memoizedRequests/getBookingConfirmation"
import { MEMBERSHIP_FAILED_ERROR } from "../types/membershipFailedError"

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

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

export async function BookingConfirmationPage({
  intl,
  lang,
  searchParams,
  config,
}: {
  intl: IntlShape
  lang: Lang
  searchParams: NextSearchParams
  config: BookingFlowConfig
}) {
  const refId = searchParams.RefId?.toString()

  if (!refId) {
    notFound()
  }

  const cookieStore = await cookies()
  const sig = cookieStore.get("bcsig")?.value

  if (!sig) {
    redirect(`/${lang}`)
  }

  const expire = Number(decrypt(sig))
  // eslint-disable-next-line react-hooks/purity
  const now = Math.floor(Date.now() / 1000)
  if (typeof expire === "number" && !isNaN(expire) && now > expire) {
    redirect(`/${lang}`)
  }

  void getBookingConfirmation(refId)

  const membershipFailedError =
    searchParams.errorCode === MEMBERSHIP_FAILED_ERROR

  return (
    <BookingFlowConfig config={config}>
      <BookingConfirmation
        intl={intl}
        refId={refId}
        membershipFailedError={membershipFailedError}
      />
    </BookingFlowConfig>
  )
}
