"use client"; import { FieldValues, useForm, Controller } from "react-hook-form"; import { cn } from "@heroui/theme"; import { Radio, RadioGroup } from "@heroui/radio"; import { useState } from "react"; import { ProceedToCheckout } from "../ProceedToCheckout"; import { useCustomToast } from "@utils/hooks/useToast"; import { useCheckout } from "@utils/hooks/useCheckout"; import { CustomRadioProps, ShippingMethodType } from "@components/checkout/type"; import { useDispatch } from "react-redux"; import { updateCart } from "@/store/slices/cart-slice"; export default function ShippingMethod({ shippingMethod, selectedShippingRate, currentStep }: { shippingMethod?: ShippingMethodType[]; selectedShippingRate?: any; methodDesc?: string; currentStep?: string; }) { const { isSaving, saveCheckoutShipping } = useCheckout(); const { showToast } = useCustomToast(); const [isOpen, setIsOpen] = useState(currentStep !== "shipping"); const [prevValues, setPrevValues] = useState({ currentStep, selectedShippingRate }); if (currentStep !== prevValues.currentStep || selectedShippingRate !== prevValues.selectedShippingRate) { setPrevValues({ currentStep, selectedShippingRate }); if (currentStep === "shipping") { setIsOpen(false); } else if (selectedShippingRate) { setIsOpen(true); } } const { control, handleSubmit } = useForm({ mode: "onSubmit", defaultValues: { method: selectedShippingRate ?? "", }, }); const selectedMethodTitle = shippingMethod?.find( (method) => method.method === selectedShippingRate )?.label; const selectedMethodPrice = shippingMethod?.find( (method) => method.method === selectedShippingRate )?.price; const dispatch = useDispatch(); const onSubmit = async (data: FieldValues) => { if (!data?.method) { showToast("Please Choose the Shipping Method", "warning"); return; } try { const selectedRate = shippingMethod?.find(m => m.method === data.method); if (selectedRate) { dispatch(updateCart({ // shippingMethod: selectedRate?.method || "", selectedShippingRate: selectedRate?.method || "", selectedShippingRateTitle: selectedRate?.label || "", })); } await saveCheckoutShipping(data?.method); } catch { showToast("Failed to save shipping method. Please try again."); } }; return (
{(selectedShippingRate) ? ( isOpen ? ( <>

Shipping Method

{selectedMethodTitle} (${selectedMethodPrice})

Shipping Method

{selectedMethodTitle} (${selectedMethodPrice})

) : (
{Array.isArray(shippingMethod) && ( ( {shippingMethod.map((method: any) => ( {method?.label} ))} )} /> )}
) ) : (
{Array.isArray(shippingMethod) && ( { return ( { field.onChange(value); }} > {shippingMethod.map((method : any) => ( {method?.label} ))} ) }} /> )}
)}
); } const CustomRadio = (props: CustomRadioProps) => { const { children, className, ...otherProps } = props; return ( {children} ); };