"use client"

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

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

import { createQueryParamsForEnterDetails } from "@/components/HotelReservation/SelectRate/RoomSelection/utils"
import LoadingSpinner from "@/components/LoadingSpinner"

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

export default function PaymentCallback({
  returnUrl,
  searchObject,
}: {
  returnUrl: string
  searchObject: URLSearchParams
}) {
  const router = useRouter()

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

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

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

  return <LoadingSpinner />
}
