import { PaymentCallbackStatusEnum } from "@scandic-hotels/common/constants/paymentCallbackStatusEnum"
import { logger } from "@scandic-hotels/common/logger"
import { LoadingSpinner } from "@scandic-hotels/design-system/LoadingSpinner"
import { BookingErrorCodeEnum } from "@scandic-hotels/trpc/enums/bookingErrorCode"

import { serverClient } from "@/lib/trpc/server"

import GuaranteeCallback from "@/components/HotelReservation/MyStay/Ancillaries/GuaranteeCallback"
import TrackGuarantee from "@/components/HotelReservation/MyStay/TrackGuarantee"

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

type GuaranteeMyStayCallbackProps = {
  lang: Lang
  myStayUrl: string
  refId: string
  status: PaymentCallbackStatusEnum
  confirmationNumber?: string
  isAncillaryFlow?: boolean
}

export default async function GuaranteeCallbackPage({
  lang,
  myStayUrl,
  refId,
  status,
  confirmationNumber,
  isAncillaryFlow,
}: GuaranteeMyStayCallbackProps) {
  const searchObject = new URLSearchParams()

  if (status === PaymentCallbackStatusEnum.Success && confirmationNumber) {
    if (isAncillaryFlow) {
      return (
        <GuaranteeCallback
          returnUrl={myStayUrl}
          refId={refId}
          confirmationNumber={confirmationNumber}
          lang={lang}
        />
      )
    }
    logger.debug(`[gla-payment-callback] redirecting to: ${myStayUrl}`)
    return <TrackGuarantee status={status} redirectUrl={myStayUrl} />
  }

  let errorMessage = undefined

  if (refId) {
    try {
      const caller = await serverClient()
      const bookingStatus = await caller.booking.status({
        refId,
      })

      const { booking } = bookingStatus

      const error = booking.errors.find((e) => e.errorCode)
      errorMessage =
        error?.description ??
        `No error message found for booking ${confirmationNumber}, status: ${status}`

      searchObject.set(
        "errorCode",
        error
          ? error.errorCode.toString()
          : BookingErrorCodeEnum.TransactionFailed
      )
    } catch {
      logger.error(
        `[gla-payment-callback] failed to get booking status for ${confirmationNumber}, status: ${status}`
      )
      if (status === PaymentCallbackStatusEnum.Cancel) {
        searchObject.set("errorCode", BookingErrorCodeEnum.TransactionCancelled)
      } else if (status === PaymentCallbackStatusEnum.Error) {
        searchObject.set("errorCode", BookingErrorCodeEnum.TransactionFailed)
        errorMessage = `Failed to get booking status for ${confirmationNumber}, status: ${status}`
      }
    }

    if (errorMessage) {
      logger.error(errorMessage)
    }

    if (isAncillaryFlow) {
      searchObject.set("ancillary", "ancillary")
    }

    return (
      <TrackGuarantee
        status={status}
        isAncillaryFlow={!!isAncillaryFlow}
        redirectUrl={`${myStayUrl}&${searchObject.toString()}`}
        errorMessage={errorMessage}
      />
    )
  }

  return <LoadingSpinner />
}
