"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 { serializeBookingSearchParams } 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 = serializeBookingSearchParams(
        detailsStorage.booking,
        {
          initialSearchParams: searchObject,
        }
      )

      const glaSessionData = readGlaFromSessionStorage()

      if (status === PaymentCallbackStatusEnum.Cancel) {
        if (glaSessionData) {
          trackEvent({
            event: "glaCardSaveCancelled",
            hotelInfo: {
              hotelId: glaSessionData.hotelId,
              lateArrivalGuarantee: glaSessionData.lateArrivalGuarantee,
              guaranteedProduct: "room",
            },
            paymentInfo: {
              hotelId: glaSessionData.hotelId,
              status: "glacardsavecancelled",
            },
          })
        } else {
          trackPaymentEvent({
            event: "paymentCancel",
            hotelId: detailsStorage.booking.hotelId,
            status: "cancelled",
          })
        }
      }
      if (status === PaymentCallbackStatusEnum.Error) {
        if (glaSessionData) {
          trackEvent({
            event: "glaCardSaveFailed",
            hotelInfo: {
              hotelId: glaSessionData.hotelId,
              lateArrivalGuarantee: glaSessionData.lateArrivalGuarantee,
              guaranteedProduct: "room",
            },
            paymentInfo: {
              hotelId: glaSessionData.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 />
}
