"use client"

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

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

import { detailsStorageName } from "../../../../stores/enter-details"
import { serializeBookingSearchParams } from "../../../../utils/url"
import {
  clearPaymentInfoSessionStorage,
  readPaymentInfoFromSessionStorage,
} from "../helpers"
import { clearGlaSessionStorage, readGlaFromSessionStorage } from "./helpers"

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

export 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()
      const paymentInfoSessionData = readPaymentInfoFromSessionStorage()

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

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

  return <LoadingSpinner fullPage />
}
