/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState } 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 {
  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<string, any>;
  step2: Record<string, any>;
  step3: Record<string, any>;
}
const CreateOrderFooter: React.FC<CreateOrderFooterProps> = ({
  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);

  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<boolean>(false);
    const [orderPlacedModalVisible, setOrderPlacedModalVisible] =
     useState<boolean>(false); 
     const [placedOrderNumber, setPlacedOrderNumber] = useState<string | number>(
     ""
   );
  const [paymentSuccess, setPaymentSuccess] = React.useState<boolean>(false);
  const { step1, step2, step3 } = useAppSelector((state) => state.createOrder);
  const [openPlaceOrderModal, setOpenPlaceOrderModal] =
    React.useState<boolean>(false);
  const [openOrderSuccessModal, setOpenOrderSuccessModal] =
    React.useState<boolean>(false);
  const togglePlaceOrder = () => setOpenPlaceOrderModal(!openPlaceOrderModal);
  const toggleOrderSuccessModal = () =>
    setOpenOrderSuccessModal(!openOrderSuccessModal);
  const [openPaymentConfirmModal, setOpenPaymentConfirmModal] =
    React.useState<boolean>(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?.orderNumber || "N/A";

        setPlacedOrderNumber(orderNumber);
        setOrderPlacedModalVisible(true);
    // Success modal like your screenshot
    // Swal.fire({
    //   iconHtml: `<div style="background-color:#00C851; border-radius:50%; width:60px; height:60px; display:flex; align-items:center; justify-content:center; margin:0 auto;">
    //                <i class="ri-check-line" style="color:white; font-size:28px;"></i>
    //              </div>`,
    //   title: `<span style="font-size:1.25em; font-weight:600; display:block; margin-top:10px;">Your order has been placed successfully!</span>`,
    //   html: `
    //     <div style="font-size:1em; line-height:1.4em; text-align:center; margin-top:10px;">
    //       Thank you for shipping with us!<br/>
    //       We've received your order No.<strong>${orderNumber}</strong>.<br/>
    //       A pickup agent will arrive shortly to collect your package.<br/>
    //       Please make the payment at the time of pickup.<br/>
    //       <small style="color:#888;">* Final charges may vary based on package weight, size, and international courier rates.</small>
    //     </div>
    //   `,
    //   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 || {};
            const step1Data = {
              ...step1,
              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);
            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);
          // Swal.fire({
          //   icon: "error",
          //   title: "Oops...",
          //   text: response.message || "Something went wrong. Please try again.",
          //   confirmButtonText: "OK",
          // });
        }
      }
    } catch (error) {
      console.error("Error during API call:", error);
    } finally {
      setIsLoading(false);
    }
  };

  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 && <HourGlassLoader />}
                 <OrderPlacedModal
             visible={orderPlacedModalVisible}
             orderNumber={placedOrderNumber}
             onMyOrders={() => {
               setOrderPlacedModalVisible(false);
               router.push("/my-orders?_=in_progress");
             }}
             onHome={() => {
               setOrderPlacedModalVisible(false);
               router.push("/dashboard");
             }}
       onClose={() => setOrderPlacedModalVisible(false)}
          />
      {step === 4 ? (
        <div className="card-bottom my-3 d-flex justify-content-between gap-2">
          {/* <button
            onClick={handleAddMore}
            className="btn btn-m rounded-m delybell-primary font-700 text-uppercase flex-fill text-center"
          >
            <i className="fa fa-plus me-1" /> Add More
          </button> */}
                      <a
              href="#"
              onClick={() => {
                handleNext(true);
                backButtonFn();
              }}
              data-menu="menu-wizard-step-2"
              className="btn btn-m rounded-m delybell-dark font-700 text-uppercase flex-fill text-center"
            >
              <i className="fa fa-arrow-left-long ms-1" /> Back
            </a>
          <button
            onClick={handlePlaceOrder}
            className="btn btn-m rounded-m bg-green2 font-700 text-uppercase flex-fill text-center"
          >
            <i className="fa fa-check me-1" /> Place Order
          </button>
        </div>
      ) : (
        <div className="card-bottom step2-card-bottom py-3 d-flex justify-content-between gap-2 bg-white">
          {backButton ? (
            <a
              href="#"
              onClick={() => {
                handleNext(true);
                backButtonFn();
              }}
              data-menu="menu-wizard-step-2"
              className="btn btn-m rounded-m delybell-dark font-700 text-uppercase flex-fill text-center"
            >
              <i className="fa fa-arrow-left-long ms-1" /> Back
            </a>
          ) : (
            ""
          )}
          {step === 1 ? (
            <a
              href="/dashboard#"
              data-menu="menu-wizard-step-2"
              className="btn btn-m rounded-m delybell-dark font-700 text-uppercase flex-fill text-center"
            >
              <i className="fa fa-home ms-1" />
              &nbsp; Home
            </a>
          ) : (
            ""
          )}
          <a
            href="#"
            onClick={() => {
              // e.preventDefault();
              handleNext();
            }}
            data-menu="menu-wizard-step-2"
            className="btn btn-m rounded-m delybell-primary font-700 text-uppercase flex-fill text-center"
          >
            Next <i className="fa fa-arrow-right-long ms-1" />
          </a>
        </div>
      )}
      {openPlaceOrderModal && (
        <Modal
          show={openPlaceOrderModal}
          onHide={togglePlaceOrder}
          header={false}
          title=""
          fullscreen={"xl"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >
          <PlaceOrderModal
            onClose={togglePlaceOrder}
            openPaymentConfirmModal={openPaymentConfirmModal}
            togglePaymentConfirm={togglePaymentConfirm}
            handleMakePayment={handleMakePayment}
          />
        </Modal>
      )}
      {openPaymentConfirmModal && (
        <Modal
          show={openPaymentConfirmModal}
          onHide={togglePaymentConfirm}
          header={false}
          title=""
          fullscreen={"xl"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >
          <PaymentConfirmModal
            onClose={() => {
              togglePaymentConfirm();
              toggleOrderSuccessModal();
            }}
            paymentSuccess={paymentSuccess}
          />
        </Modal>
      )}
      {openOrderSuccessModal && (
        <Modal
          show={openOrderSuccessModal}
          onHide={toggleOrderSuccessModal}
          header={false}
          title=""
          fullscreen={"xl"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >
          <OrderSuccessModal
            onClose={toggleOrderSuccessModal}
            orderLength={savedOrder?.length || 0}
          />
        </Modal>
      )}
    </>
  );
};

export default CreateOrderFooter;
