"use client"

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

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

import { readGlaFromSessionStorage } from "@/components/HotelReservation/EnterDetails/Payment/PaymentCallback/helpers"
import LoadingSpinner from "@/components/LoadingSpinner"
import { trackEvent } from "@/utils/tracking/base"

import {
  buildAncillaryPackages,
  getAncillarySessionData,
} from "../../Ancillaries/utils"

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 } = sessionData || {}

      const packages =
        formData && selectedAncillary
          ? buildAncillaryPackages(formData, selectedAncillary)
          : []

      trackEvent({
        event,
        paymentInfo: { status },
        ancillaries: packages.map((pkg) => ({
          hotelId: selectedAncillary?.hotelId,
          productId: pkg.code,
          productUnits: pkg.quantity,
          productPoints: selectedAncillary?.points,
          productDeliveryTime: formData?.deliveryTime,
          productPrice: selectedAncillary?.price,
          productName: selectedAncillary?.title,
          productCategory: selectedAncillary?.categoryName,
        })),
        lateArrivalGuarantee: "yes",
        guaranteedProduct: "room + ancillary",
      })
    }

    const trackGuaranteePaymentEvent = (event: string, status: string) => {
      trackEvent({
        event,
        hotelInfo: {
          lateArrivalGuarantee: "yes",
          guaranteedProduct: "room",
        },
        paymentInfo: {
          status,
          ...(errorMessage && { errorMessage }),
        },
      })
    }

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