/* eslint-disable @typescript-eslint/no-explicit-any */ import React, { useState, useEffect } from "react"; import { Modal } from "react-bootstrap"; import PlaceOrderModal from "../../../Modal/PlaceOrderModal"; import PaymentConfirmModal from "../../../Modal/PaymentConfirmModal"; import { createOrder, makePayment } from "../../../../Api/OrderApi"; import { useAppSelector } from "@/Redux/Hooks"; import HourGlassLoader from "../../../Loader/Loader"; import { useDispatch } from "react-redux"; import { resetOrderData, saveStepData } from "@/Redux/Reducers/CreateOrderSlice"; import Swal from "sweetalert2"; import OrderSuccessModal from "../../../Modal/OrderSuccessModal"; import { useRouter, useSearchParams } from "next/navigation"; import { OrderFlowType } from "@/Constant/enums"; import { placeInternationalOrder } from "../../../../Api/InternationalOrderApi"; import OrderPlacedModal from "./Step3/OrderPlacedModal"; interface CreateOrderFooterProps { step: number; setStep: (step: number) => void; validation: () => void; backButton?: boolean; backButtonFn?: () => void; isEditMode?: boolean; defaultOrderDetails?: any; isInternational?: boolean; } interface CreateOrderState { step1: Record; step2: Record; step3: Record; } const CreateOrderFooter: React.FC = ({ step, setStep, validation, backButton = false, backButtonFn = () => {}, defaultOrderDetails = {}, isEditMode = false, // handleFuturePickupConfirm = () => {}, isInternational = false, }) => { const router = useRouter(); const [savedOrder, setSavedOrder] = useState([]); const dispatch = useDispatch(); const searchParams: any = useSearchParams(); const orderId: any = searchParams?.get("orderId") || ""; const createOrderData: any = useAppSelector((state) => state.createOrder); // Fetch draft details when in edit mode and populate Redux useEffect(() => { const fetchDraftDetails = async (id: string) => { if (!id) return; try { setIsLoading(true); const res = await fetch(`/customer/international/draft/details/${id}`); const json = await res.json(); if (json?.status && json?.data) { const data = json.data; // Try to map to steps if API provides sections; otherwise stash into step1 try { if (data.step1 || data.step2 || data.step3) { if (data.step1) dispatch(saveStepData({ step: "step1", data: data.step1 })); if (data.step2) dispatch(saveStepData({ step: "step2", data: data.step2 })); if (data.step3) dispatch(saveStepData({ step: "step3", data: data.step3 })); } else { // fallback: store entire payload in step1 (adjust if your API returns different keys) dispatch(saveStepData({ step: "step1", data })); } } catch (err) { console.error("Error mapping draft details to steps:", err); dispatch(saveStepData({ step: "step1", data })); } } else { console.warn("Draft details fetch returned no data:", json); } } catch (err) { console.error("Error fetching draft details:", err); } finally { setIsLoading(false); } }; if (orderId) { fetchDraftDetails(orderId); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [orderId]); const handleSave = (stepKey: keyof CreateOrderState, data: any) => { const updatedStepData = { ...createOrderData[stepKey], // Merge existing step data ...data, // Add/update new fields }; dispatch(saveStepData({ step: stepKey, data: updatedStepData })); // ✅ Send merged }; const [isLoading, setIsLoading] = React.useState(false); const [orderPlacedModalVisible, setOrderPlacedModalVisible] = useState(false); const [placedOrderNumber, setPlacedOrderNumber] = useState( "", ); const [paymentSuccess, setPaymentSuccess] = React.useState(false); const { step1, step2, step3 } = useAppSelector((state) => state.createOrder); const [openPlaceOrderModal, setOpenPlaceOrderModal] = React.useState(false); const [openOrderSuccessModal, setOpenOrderSuccessModal] = React.useState(false); const togglePlaceOrder = () => setOpenPlaceOrderModal(!openPlaceOrderModal); const toggleOrderSuccessModal = () => setOpenOrderSuccessModal(!openOrderSuccessModal); const [openPaymentConfirmModal, setOpenPaymentConfirmModal] = React.useState(false); const togglePaymentConfirm = () => setOpenPaymentConfirmModal(!openPaymentConfirmModal); // const handleAddMore = async () => { // window.location.href = "/create-order"; // dispatch(resetOrderData()); // setStep(1); // }; const handlePlaceOrder = async () => { try { setIsLoading(true); // Place the order API call const response = await placeInternationalOrder({}); if (!response?.status) { Swal.fire({ icon: "error", title: "Order Failed", text: response?.message || "Something went wrong. Please try again.", }); return; } const orderNumber = response?.data?.orders?.[0]?.generated_order_id || "N/A"; setPlacedOrderNumber(orderNumber); setOrderPlacedModalVisible(true); localStorage.removeItem("CREATE_INTL_STEP1"); localStorage.removeItem("CREATE_INTL_STEP2"); localStorage.removeItem("CREATE_INTL_STEP3"); localStorage.removeItem("CREATE_INTL_STEP4"); dispatch(resetOrderData()); // Success modal like your screenshot // Swal.fire({ // iconHtml: `
// //
`, // title: `Your order has been placed successfully!`, // html: ` //
// Thank you for shipping with us!
// We've received your order No.${orderNumber}.
// A pickup agent will arrive shortly to collect your package.
// Please make the payment at the time of pickup.
// * Final charges may vary based on package weight, size, and international courier rates. //
// `, // showCancelButton: true, // confirmButtonText: "My Orders", // cancelButtonText: "Home Page", // customClass: { // confirmButton: "swal-confirm-btn", // cancelButton: "swal-cancel-btn", // popup: "swal-custom-popup", // }, // reverseButtons: true, // allowOutsideClick: false, // allowEscapeKey: false, // }).then((result) => { // if (result.isConfirmed) { // window.location.href = "/my-orders?_=in_progress"; // } else if (result.dismiss === Swal.DismissReason.cancel) { // window.location.href = "/dashboard"; // } // }); } catch (error) { console.error("Order placement error:", error); Swal.fire({ icon: "error", title: "Something Went Wrong", text: "Please try again or contact support.", }); } finally { setIsLoading(false); } }; const handleNext = async (isBack: boolean = false) => { try { if ( step === 2 && !step3?.step3?.preview?.calculatedTotalShippingCharge && !isInternational ) { const result = await Swal.fire({ icon: "warning", title: "Shipping Charge Not Available", text: "Shipping charge could not be calculated at the moment. Do you still want to continue without it? Please contact admin or customer service if you're unsure.", showCancelButton: true, confirmButtonText: "Yes, Continue", cancelButtonText: "No, Go Back", customClass: { confirmButton: "delybell-primary px-4", cancelButton: "delybell-dark", }, reverseButtons: true, }); if (result.dismiss === Swal.DismissReason.cancel) { return; } } // if(!step1?.package_details && isEditMode && defaultOrderDetails) { // } const error: any = await validation(); console.log(error, "stepp"); if (error) { if (isInternational) { if (!isBack) setStep(step + 1); return; } let dataToSend: any = {}; console.log(step, "stepstepstepstep"); switch (step) { case 1: dataToSend = (step1?.package_details?.length === 0 || step1?.packageDetails?.length === 0 || !step1?.package_details) && isEditMode && defaultOrderDetails ? { ...step1, ...defaultOrderDetails, packageDetails: defaultOrderDetails?.order_package_list, } : { ...step1 }; break; case 2: dataToSend = { ...step2 }; break; case 3: dataToSend = { ...step3 }; break; default: throw new Error("Invalid step"); } const packageDisable: any = searchParams.get("packageDisable"); const dataWithStep: any = { ...dataToSend, step: step === 2 ? 3 : step, }; if (packageDisable === "true") dataWithStep.orderFlowType = { id: OrderFlowType.Return, name: "Return", }; let updatedDataWithStep = dataWithStep; if (step1?.codDetails?.codEnabled) { updatedDataWithStep = { ...dataWithStep, codDetails: { ...(dataWithStep.codDetails ?? {}), codEnabled: step1.codDetails.codEnabled, codAmount: step1.codDetails.codAmount, }, }; } setIsLoading(true); const response = await createOrder( updatedDataWithStep, 0, step3?.step3, orderId, ); if (response?.status) { if (step === 1) { const { service_type_details, draft_order_package_list = [], totalWeight, isCod, codAmount, } = response?.data || {}; // ensure we capture draft id from response so later steps can include it const draftId = response?.data?.id || response?.data?.draft_order_id || null; const step1Data = { ...step1, draft_order_id: draftId, // <-- added to persist draft id serviceType: { id: service_type_details?.id, name: service_type_details?.name, }, packageDetails: draft_order_package_list.map((pkg: any) => ({ package_id: pkg?.package_id || 1, weight: pkg?.weight || "", package_description: pkg?.packageDescription || "", customer_input_package_value: pkg?.customerInputPackageValue || "", })), packageCount: draft_order_package_list?.length ?? 1, totalWeight: totalWeight || "", ...(isCod && { codDetails: { codEnabled: isCod, codAmount: codAmount, }, }), }; handleSave("step1", step1Data); // also keep response data accessible for other steps if needed handleSave("step3", { step1: response?.data }); } if (step === 2) { if (isBack) { const url = new URL(window.location.href); url.searchParams.set("mode", "edit"); url.searchParams.set("orderId", response?.data?.id); url.searchParams.set( "customerName", response?.data?.destinationCustomerName, ); window.history.replaceState({}, "", url); const { deliveryInstructions, destinationAddress, destinationAlternateNumber, destinationMobileNumber, destinationCustomerName, destination_road_details, destination_building_details, destinationFlatOrOfficeNumber, destination_block_details, customerInputOrderId, } = response?.data || {}; const step2Data = { orderId: customerInputOrderId || "", draft_order_id: response?.data?.id || "", deliveryMobile: destinationMobileNumber || "", customerName: destinationCustomerName || "", altDeliveryMobile: destinationAlternateNumber || "", blockNo: { value: destination_block_details?.id, label: `${destination_block_details?.code} ${ destination_block_details?.name ? ` - ${destination_block_details?.name}` : "" }`, code: destination_block_details?.code, name: destination_block_details?.name, id: destination_block_details?.id, }, roadNo: { value: destination_road_details?.id, label: `${destination_road_details?.code} ${ destination_road_details?.name ? ` - ${destination_road_details?.name}` : "" }`, code: destination_road_details?.code, name: destination_road_details?.name, id: destination_road_details?.id, }, buildingNo: { value: destination_building_details?.id, label: `${destination_building_details?.code} ${ destination_building_details?.name ? ` - ${destination_building_details?.name}` : "" }`, code: destination_building_details?.code, name: destination_building_details?.name, id: destination_building_details?.id, }, flatNo: destinationFlatOrOfficeNumber || "", destinationAddress: destinationAddress || "", remarks: deliveryInstructions || "", }; handleSave("step2", { ...step2, ...step2Data }); setStep(1); } else router.replace("/create-international-order"); } if (!isBack) setStep(step + 1); } else { setStep(step + 1); console.error("Failed to save details:", response.message); } } } catch (error) { console.error("Error during API call:", error); } finally { setIsLoading(false); } }; // Small helper: unified back handler that only triggers the supplied back action const handleBackClick = (cb?: () => void) => { try { if (typeof cb === "function") cb(); } catch (err) { console.error("Back handler error:", err); } }; const handleMakePayment = async () => { try { if (!createOrderData?.step3?.makePayment?.date) Swal.fire({ icon: "warning", title: "Oops...", text: "Please select date", // text: response.message || "Something went wrong. Please try again.", confirmButtonText: "OK", }); else if (!createOrderData?.step3?.makePayment?.time) Swal.fire({ icon: "warning", title: "Oops...", text: "Please select time", // text: response.message || "Something went wrong. Please try again.", confirmButtonText: "OK", }); else { setIsLoading(true); const response = await makePayment({ pickup_date: createOrderData?.step3?.makePayment?.date || "", pickup_slot_type: createOrderData?.step3?.makePayment?.time || 1, }); if (response.status) { setSavedOrder(response?.data || []); togglePlaceOrder(); // togglePaymentConfirm(); toggleOrderSuccessModal(); setPaymentSuccess(true); } else { Swal.fire({ icon: "warning", title: "Payment Failed!", text: response?.message || "Something went wrong. Please try again.", confirmButtonText: "OK", customClass: { confirmButton: "delybell-primary px-4", cancelButton: "delybell-dark", }, }); // // Handle failure (e.g., show error toast or modal) // // togglePlaceOrder(); // togglePaymentConfirm(); // setPaymentSuccess(false); } } } catch (error) { // Handle unexpected error console.error("Payment error:", error); alert("An unexpected error occurred during payment."); } finally { setIsLoading(false); } }; return ( <> {isLoading && } {}} header={false} title="" fullscreen={"md"} centered={true} classname="" // custom-center-modal address-select-modal position={"center"} > { setOrderPlacedModalVisible(false); router.push("/my-orders?_=in_progress"); }} onHome={() => { setOrderPlacedModalVisible(false); router.push("/dashboard"); }} onClose={() => setOrderPlacedModalVisible(false)} /> {step === 4 ? ( ) : ( )} {openPlaceOrderModal && ( )} {openPaymentConfirmModal && ( { togglePaymentConfirm(); toggleOrderSuccessModal(); }} paymentSuccess={paymentSuccess} /> )} {openOrderSuccessModal && ( )} ); }; export default CreateOrderFooter;