"use client"

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

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

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

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

export default function PaymentCallback({
  returnUrl,
  searchObject,
  status,
  errorMessage,
}: {
  returnUrl: string
  searchObject: URLSearchParams
  status: "error" | "success" | "cancel"
  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
      )

      if (status === "cancel") {
        trackPaymentEvent({
          event: "paymentCancel",
          hotelId: detailsStorage.booking.hotelId,
          status: "cancelled",
        })
      }
      if (status === "error") {
        trackPaymentEvent({
          event: "paymentFail",
          hotelId: detailsStorage.booking.hotelId,
          errorMessage,
          status: "failed",
        })
      }

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

  return <LoadingSpinner fullPage />
}
