"use client"

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

import { PaymentCallbackStatusEnum } from "@scandic-hotels/common/constants/booking"
import { trackEvent } from "@scandic-hotels/common/tracking/base"
import { LoadingSpinner } from "@scandic-hotels/design-system/LoadingSpinner"

import {
  clearGlaSessionStorage,
  readGlaFromSessionStorage,
} from "@/components/HotelReservation/EnterDetails/Payment/PaymentCallback/helpers"
import { getAncillarySessionData } from "@/components/HotelReservation/MyStay/utils/ancillaries"
import {
  buildAncillariesTracking,
  buildBreakfastTracking,
} from "@/utils/tracking/myStay"

interface TrackGuaranteeProps {
  status: string
  isAncillaryFlow?: boolean
  redirectUrl: string
  errorMessage?: string
}

export default function TrackGuarantee({
  status,
  isAncillaryFlow = false,
  redirectUrl,
  errorMessage,
}: TrackGuaranteeProps) {
  const router = useRouter()

  useEffect(() => {
    const trackAncillaryPaymentEvent = (event: string, status: string) => {
      const sessionData = getAncillarySessionData()
      const { formData, selectedAncillary, packages, breakfastData } =
        sessionData || {}

      trackEvent({
        event,
        paymentInfo: { status },
        hotelInfo: {
          hotelId: selectedAncillary?.hotelId,
          lateArrivalGuarantee: "yes",
          guaranteedProduct: "room + ancillary",
        },
        ancillaries: breakfastData
          ? buildBreakfastTracking(breakfastData)
          : buildAncillariesTracking(
              packages ?? [],
              selectedAncillary,
              formData?.deliveryTime
            ),
      })
    }

    const trackGuaranteePaymentEvent = (event: string, status: string) => {
      const glaSessionData = readGlaFromSessionStorage()
      trackEvent({
        event,
        hotelInfo: {
          hotelId: glaSessionData?.hotelId,
          lateArrivalGuarantee: "yes",
          guaranteedProduct: "room",
        },
        paymentInfo: {
          status,
          type: glaSessionData?.paymentMethod,
          isSavedCreditCard: glaSessionData?.isSavedCreditCard,
          ...(errorMessage && { errorMessage }),
        },
      })
      clearGlaSessionStorage()
    }

    switch (status) {
      case PaymentCallbackStatusEnum.Success:
        const glaSessionData = readGlaFromSessionStorage()
        trackEvent({
          event: "guaranteeBookingSuccess",
          hotelInfo: {
            hotelId: glaSessionData?.hotelId,
            lateArrivalGuarantee: "yes",
            guaranteedProduct: "room",
          },
          paymentInfo: {
            type: glaSessionData?.paymentMethod,
            hotelId: glaSessionData?.hotelId,
            isSavedCreditCard: glaSessionData?.isSavedCreditCard,
          },
        })
        clearGlaSessionStorage()
        break

      case PaymentCallbackStatusEnum.Cancel:
        isAncillaryFlow
          ? trackAncillaryPaymentEvent(
              "GuaranteeCancelAncillary",
              "glacardsavecancelled"
            )
          : trackGuaranteePaymentEvent(
              "glaCardSaveCancelled",
              "glacardsavecancelled"
            )
        break

      case PaymentCallbackStatusEnum.Error:
        isAncillaryFlow
          ? trackAncillaryPaymentEvent(
              "GuaranteeFailAncillary",
              "glacardsavefailed"
            )
          : trackGuaranteePaymentEvent("glaCardSaveFailed", "glacardsavefailed")
        break
    }

    router.replace(redirectUrl)
  }, [status, isAncillaryFlow, redirectUrl, errorMessage, router])

  return <LoadingSpinner />
}
