"use client"

import { usePathname, useRouter, useSearchParams } from "next/navigation"
import { useCallback, useEffect } from "react"
import { useIntl } from "react-intl"

import { BookingErrorCodeEnum } from "@/constants/booking"

import { toast } from "@/components/TempDesignSystem/Toasts"

export function useGuaranteePaymentFailedToast() {
  const intl = useIntl()
  const searchParams = useSearchParams()
  const pathname = usePathname()
  const router = useRouter()

  const getErrorMessage = useCallback(
    (errorCode: string | null) => {
      switch (errorCode) {
        case "AncillaryFailed":
          return intl.formatMessage({
            defaultMessage:
              "The product could not be added. Your booking is guaranteed. Please try again.",
          })
        default:
          return intl.formatMessage({
            defaultMessage:
              "We had an issue guaranteeing your booking. Please try again.",
          })
      }
    },
    [intl]
  )

  useEffect(() => {
    const errorCode = searchParams.get("errorCode")
    const errorMessage = getErrorMessage(errorCode)
    if (!errorCode || errorCode === BookingErrorCodeEnum.TransactionCancelled)
      return

    const toastType =
      errorCode === BookingErrorCodeEnum.TransactionCancelled
        ? "warning"
        : "error"
    toast[toastType](errorMessage)

    const ancillary = searchParams.get("ancillary")
    if ((errorCode && ancillary) || errorCode === "AncillaryFailed") {
      return
    }

    const queryParams = new URLSearchParams(searchParams.toString())
    queryParams.delete("errorCode")

    router.push(`${pathname}?${queryParams.toString()}`)
  }, [searchParams, pathname, router, getErrorMessage])
}
