"use client"; import { Controller, FieldValues, useForm } from "react-hook-form"; import { cn } from "@heroui/theme"; import { Radio, RadioGroup } from "@heroui/radio"; import { useState } from "react"; import { useCustomToast } from "@utils/hooks/useToast"; import { useCheckout } from "@utils/hooks/useCheckout"; import { ProceedToCheckout } from "../ProceedToCheckout"; import { CustomRadioProps } from "@components/checkout/type"; import { useDispatch } from "react-redux"; import { updateCart } from "@/store/slices/cart-slice"; export default function PaymentMethod({ selectedPayment, methods, currentStep, }: { selectedPayment?: string; methods: any; currentStep?: string; }) { const { showToast } = useCustomToast(); const { isPaymentLoading, saveCheckoutPayment } = useCheckout(); const [isOpen, setIsOpen] = useState(currentStep !== "payment"); const [prevValues, setPrevValues] = useState({ currentStep, selectedPayment, }); if ( currentStep !== prevValues.currentStep || selectedPayment !== prevValues.selectedPayment ) { setPrevValues({ currentStep, selectedPayment }); if (currentStep === "payment") { setIsOpen(false); } else if (selectedPayment) { setIsOpen(true); } } const { handleSubmit, control } = useForm({ mode: "onSubmit", defaultValues: { method: selectedPayment ?? "", }, }); const selectedMethodLabelPrior = methods?.find( (method: any) => method?.method === selectedPayment, )?.title; const dispatch = useDispatch(); const onSubmit = async (data: FieldValues) => { if (!data?.method) { showToast("Please Choose the Payment Method", "warning"); return; } try { const selectedMethod = methods?.find( (m: any) => m?.method === data?.method, ); if (selectedMethod) { dispatch( updateCart({ paymentMethod: selectedMethod?.method || "", paymentMethodTitle: selectedMethod?.title || "", }), ); } await saveCheckoutPayment(data.method); } catch { showToast("Failed to save payment method. Please try again."); } }; return ( <> {selectedPayment ? ( isOpen ? ( <>
Payment Method
{selectedMethodLabelPrior as string}
Payment Method
{selectedMethodLabelPrior as string}