"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 { DetailsState } 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: Record<
        "state",
        Pick<DetailsState, "booking">
      > = JSON.parse(bookingData)
      const searchParams = createQueryParamsForEnterDetails(
        detailsStorage.state.booking,
        searchObject
      )

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

  return <LoadingSpinner />
}
