Files
web/apps/scandic-web/components/HotelReservation/EnterDetails/Payment/PaymentAlert/index.tsx

86 lines
2.3 KiB
TypeScript

"use client"
import { usePathname, useSearchParams } from "next/navigation"
import { useEffect, useState } from "react"
import { useIntl } from "react-intl"
import { BookingErrorCodeEnum } from "@/constants/booking"
import { useEnterDetailsStore } from "@/stores/enter-details"
import Alert from "@/components/TempDesignSystem/Alert"
import styles from "./paymentAlert.module.css"
import { AlertTypeEnum } from "@/types/enums/alert"
function useBookingErrorAlert() {
const updateSearchParams = useEnterDetailsStore(
(state) => state.actions.updateSeachParamString
)
const intl = useIntl()
const searchParams = useSearchParams()
const pathname = usePathname()
const errorCode = searchParams.get("errorCode")
const errorMessage = getErrorMessage(errorCode)
const severityLevel =
errorCode === BookingErrorCodeEnum.TransactionCancelled
? AlertTypeEnum.Warning
: AlertTypeEnum.Alarm
const [showAlert, setShowAlert] = useState(!!errorCode)
function getErrorMessage(errorCode: string | null) {
switch (errorCode) {
case BookingErrorCodeEnum.TransactionCancelled:
return intl.formatMessage({
defaultMessage: "You have now cancelled your payment.",
})
default:
return intl.formatMessage({
defaultMessage:
"We had an issue processing your booking. Please try again. No charges have been made.",
})
}
}
function discardAlert() {
setShowAlert(false)
const queryParams = new URLSearchParams(searchParams.toString())
queryParams.delete("errorCode")
updateSearchParams(queryParams.toString())
window.history.replaceState({}, "", `${pathname}?${queryParams.toString()}`)
}
return { showAlert, errorMessage, severityLevel, discardAlert, setShowAlert }
}
interface PaymentAlertProps {
isVisible?: boolean
}
export default function PaymentAlert({ isVisible = false }: PaymentAlertProps) {
const { showAlert, errorMessage, severityLevel, discardAlert, setShowAlert } =
useBookingErrorAlert()
useEffect(() => {
if (isVisible) {
setShowAlert(true)
}
}, [isVisible, setShowAlert])
if (!showAlert) return null
return (
<div className={styles.wrapper}>
<Alert
type={severityLevel}
variant="inline"
text={errorMessage}
close={discardAlert}
/>
</div>
)
}