"use client"

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

import { PaymentCallbackStatusEnum } from "@/constants/booking"
import { detailsStorageName } from "@/stores/enter-details"

import LoadingSpinner from "@/components/LoadingSpinner"
import { trackPaymentEvent } from "@/utils/tracking"
import { trackEvent } from "@/utils/tracking/base"
import { convertObjToSearchParams } from "@/utils/url"

import { clearGlaSessionStorage, readGlaFromSessionStorage } from "./helpers"

import type { PersistedState } from "@/types/stores/enter-details"

export default function HandleErrorCallback({
  returnUrl,
  searchObject,
  status,
  errorMessage,
}: {
  returnUrl: string
  searchObject: URLSearchParams
  status: PaymentCallbackStatusEnum
  errorMessage?: string
}) {
  const router = useRouter()

  useEffect(() => {
    const bookingData = window.sessionStorage.getItem(detailsStorageName)

    if (bookingData) {
      const detailsStorage: PersistedState = JSON.parse(bookingData)
      const searchParams = convertObjToSearchParams(
        detailsStorage.booking,
        searchObject
      )

      const lateArrivalGuarantee = readGlaFromSessionStorage()

      if (status === PaymentCallbackStatusEnum.Cancel) {
        if (lateArrivalGuarantee) {
          trackEvent({
            event: "glaCardSaveCancelled",
            hotelInfo: {
              hotelId: detailsStorage.booking.hotelId,
              lateArrivalGuarantee,
              guaranteedProduct: "room",
            },
            paymentInfo: {
              hotelId: detailsStorage.booking.hotelId,
              status: "glacardsavecancelled",
            },
          })
        } else {
          trackPaymentEvent({
            event: "paymentCancel",
            hotelId: detailsStorage.booking.hotelId,
            status: "cancelled",
          })
        }
      }
      if (status === PaymentCallbackStatusEnum.Error) {
        if (lateArrivalGuarantee) {
          trackEvent({
            event: "glaCardSaveFailed",
            hotelInfo: {
              hotelId: detailsStorage.booking.hotelId,
              lateArrivalGuarantee,
              guaranteedProduct: "room",
            },
            paymentInfo: {
              hotelId: detailsStorage.booking.hotelId,
              status: "glacardsavefailed",
            },
          })
        } else {
          trackPaymentEvent({
            event: "paymentFail",
            hotelId: detailsStorage.booking.hotelId,
            errorMessage,
            status: "failed",
          })
        }
      }
      clearGlaSessionStorage()

      if (searchParams.size > 0) {
        router.replace(`${returnUrl}?${searchParams.toString()}`)
      }
    }
  }, [returnUrl, router, searchObject, status, errorMessage])

  return <LoadingSpinner fullPage />
}
