"use client"

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

import { PaymentCallbackStatusEnum } from "@/constants/booking"

import {
  clearGlaSessionStorage,
  readGlaFromSessionStorage,
} from "@/components/HotelReservation/EnterDetails/Payment/PaymentCallback/helpers"
import { getAncillarySessionData } from "@/components/HotelReservation/MyStay/utils/ancillaries"
import LoadingSpinner from "@/components/LoadingSpinner"
import { trackEvent } from "@/utils/tracking/base"
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 glaHotelInfo = readGlaFromSessionStorage()
      trackEvent({
        event,
        hotelInfo: {
          hotelId: glaHotelInfo?.hotelId,
          lateArrivalGuarantee: "yes",
          guaranteedProduct: "room",
        },
        paymentInfo: {
          status,
          ...(errorMessage && { errorMessage }),
        },
      })
      clearGlaSessionStorage()
    }

    switch (status) {
      case PaymentCallbackStatusEnum.Success:
        const glaHotelInfo = readGlaFromSessionStorage()
        trackEvent({
          event: "guaranteeBookingSuccess",
          hotelInfo: {
            hotelId: glaHotelInfo?.hotelId,
            lateArrivalGuarantee: "yes",
            guaranteedProduct: "room",
          },
        })
        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 />
}
