"use client"

import { useRouter } from "next/navigation"
import { useEffect } from "react"

import { LoadingSpinner } from "@scandic-hotels/design-system/LoadingSpinner"
import { BookingStatusEnum } from "@scandic-hotels/trpc/enums/bookingStatus"

import { useHandleBookingStatus } from "../../../../hooks/useHandleBookingStatus"
import { MEMBERSHIP_FAILED_ERROR } from "../../../../types/membershipFailedError"
import TimeoutSpinner from "./TimeoutSpinner"
import { trackGuaranteeBookingSuccess } from "./tracking"

const validBookingStatuses = [
  BookingStatusEnum.PaymentSucceeded,
  BookingStatusEnum.BookingCompleted,
]

interface HandleStatusPollingProps {
  refId: string
  sig: string
  successRedirectUrl: string
  cardType?: string
}

export function HandleSuccessCallback({
  refId,
  sig,
  successRedirectUrl,
  cardType,
}: HandleStatusPollingProps) {
  const router = useRouter()

  useEffect(() => {
    // Cookie is used by Booking Confirmation page to validate that the user came from payment callback
    document.cookie = `bcsig=${sig}; Path=/; Max-Age=60; Secure; SameSite=Strict`
  }, [sig])

  const {
    data: bookingStatus,
    error,
    isTimeout,
  } = useHandleBookingStatus({
    refId,
    expectedStatuses: validBookingStatuses,
    maxRetries: 10,
    retryInterval: 2000,
    enabled: true,
  })

  useEffect(() => {
    if (!bookingStatus?.booking.reservationStatus) {
      return
    }

    if (
      validBookingStatuses.includes(
        bookingStatus.booking.reservationStatus as BookingStatusEnum
      )
    ) {
      trackGuaranteeBookingSuccess(cardType)
      // a successful booking can still have membership errors
      const membershipFailedError = bookingStatus.booking.errors.find(
        (e) => e.errorCode === MEMBERSHIP_FAILED_ERROR
      )
      const errorParam = membershipFailedError
        ? `&errorCode=${membershipFailedError.errorCode}`
        : ""

      router.replace(`${successRedirectUrl}${errorParam}`)
    }
  }, [bookingStatus, cardType, successRedirectUrl, router])

  if (isTimeout || error) {
    return <TimeoutSpinner />
  }

  return <LoadingSpinner fullPage />
}
