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

import { MEMBERSHIP_FAILED_ERROR } from "@scandic-hotels/common/constants/booking"
import { decrypt } from "@scandic-hotels/trpc/utils/encryption"

import { BookingConfirmation } from "../components/BookingConfirmation"
import { getBookingConfirmation } from "../trpc/memoizedRequests/getBookingConfirmation"

import type { Lang } from "@scandic-hotels/common/constants/language"
import type { BookingConfirmation as BookingConfirmationType } from "@scandic-hotels/trpc/types/bookingConfirmation"
import type { IntlShape } from "react-intl"

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

export async function BookingConfirmationPage({
  intl,
  lang,
  searchParams,
  renderTracking,
}: {
  intl: IntlShape
  lang: Lang
  searchParams: NextSearchParams
  renderTracking: (trackingProps: {
    bookingConfirmation: BookingConfirmationType
    refId: string
  }) => React.ReactNode
}) {
  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))
  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 (
    <BookingConfirmation
      intl={intl}
      refId={refId}
      membershipFailedError={membershipFailedError}
      renderTracking={renderTracking}
    />
  )
}
