"use client";

/* eslint-disable @typescript-eslint/no-explicit-any */
import Link from "next/link";
import StepMenu from "./Containers/StepMenu";
import Step1 from "./Containers/Step1";
import { useEffect, useState } from "react";
import Step2 from "./Containers/Step2";
import Step3 from "./Containers/Step3";
import Step4 from "./Containers/Step4";
import { useAppDispatch, useAppSelector } from "@/Redux/Hooks";
import { saveStepData } from "@/Redux/Reducers/CreateOrderSlice";
import HourGlassLoader from "../../Loader/Loader";
import { getDraftOrderDetails } from "../../../Api/OrderApi";
import { useSearchParams } from "next/navigation";
import { OrderFlowType } from "@/Constant/enums";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface CreateOrderState {
  step1: Record<string, any>;
  step2: Record<string, any>;
  step3: Record<string, any>;
  step4: Record<string, any>;
}

export default function CreateOrder() {
  const searchParams: any = useSearchParams();
  const packageDisable: any = searchParams.get("packageDisable");
  const dispatch = useAppDispatch();
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [step, setStep] = useState(1);
  const createOrderData: any = useAppSelector((state) => state.createOrder);
  const [defaultOrderDetails, setDefaultOrderDetails] = useState({});
  const [isEditMode, setIsEditMode] = useState(false);
  const [customerName, setCustomerName] = useState<string>("");
  const [editData, setEditData] = useState<any>({});
  const mode: any = searchParams.get("mode");
  const orderId: any = searchParams.get("orderId");

  const handleSave = (stepKey: any, data: any) => {
    const updatedStepData = {
      ...createOrderData[stepKey],
      ...data,
    };
    dispatch(saveStepData({ step: stepKey, data: updatedStepData }));
  };

  const storedUser = localStorage.getItem("ALL_DATA");

  useEffect(() => {
    const fetchOrders = async () => {
      setIsLoading(true);
      try {
        const customerNameParam: any = searchParams.get("customerName");
        const tab: any = searchParams.get("_");
        const modeParam: any = searchParams.get("mode");
        const allData = storedUser ? JSON.parse(storedUser)?.data : null;

        if (tab === "draft") {
          setStep(3);
        }

        if ((mode === "edit" || mode === "edit_order") && orderId) {
          setIsEditMode(true);
          setStep(1);

          const orderDetails: any = await getDraftOrderDetails(orderId);
          setDefaultOrderDetails(orderDetails);
          const isReturnFlow =
            orderDetails?.orderFlowType?.id === OrderFlowType?.Return;

          const step1Data = {
            serviceType: orderDetails.service_type_details
              ? {
                  id: orderDetails.service_type_details.id,
                  name: orderDetails.service_type_details.name,
                }
              : null,
            packageCount: orderDetails?.draft_order_package_list?.length || 1,
            order_package_list:
              orderDetails?.draft_order_package_list?.map((pkg: any) => ({
                package_id: pkg.packageTypeId ?? 1,
                weight: pkg?.weight ?? 1,
                package_description:
                  pkg?.packageDescription || allData?.packageDescription || "",
                customer_input_package_value:
                  pkg?.customerInputPackageValue || "0.000",
                external_package_id: pkg?.externalPackageId || "",
              })) || [],
            totalWeight: orderDetails?.totalWeight || "0.00",
            codDetails: {
              codEnabled: orderDetails?.isCod || false,
              codAmount: orderDetails?.codAmount || "0.000",
            },
          };
          dispatch(saveStepData({ step: "step1", data: step1Data }));

          const step2Data: any =
            allData?.addressFormatType?.name === "Standard"
              ? {
                  deliveryMobile: orderDetails.destinationMobileNumber || "",
                  altDeliveryMobile:
                    orderDetails.destinationAlternateNumber || "",
                  customerName: orderDetails.destinationCustomerName || "",
                  blockNo: isReturnFlow
                    ? orderDetails.pickup_block_details
                      ? {
                          id: orderDetails.pickup_block_details.id,
                          name: orderDetails.pickup_block_details.name,
                        }
                      : null
                    : orderDetails.destination_block_details
                    ? {
                        id: orderDetails.destination_block_details.id,
                        name: orderDetails.destination_block_details.name,
                      }
                    : null,
                  roadNo: isReturnFlow
                    ? orderDetails.pickup_road_details
                      ? {
                          id: orderDetails.pickup_road_details.id,
                          name: orderDetails.pickup_road_details.name,
                        }
                      : null
                    : orderDetails.destination_road_details
                    ? {
                        id: orderDetails.destination_road_details.id,
                        name: orderDetails.destination_road_details.name,
                      }
                    : null,
                  buildingNo: isReturnFlow
                    ? orderDetails.pickup_building_details
                      ? {
                          id: orderDetails.pickup_building_details.id,
                          name: orderDetails.pickup_building_details.name,
                        }
                      : null
                    : orderDetails.destination_building_details
                    ? {
                        id: orderDetails.destination_building_details.id,
                        name: orderDetails.destination_building_details.name,
                      }
                    : null,
                  flatNo: isReturnFlow
                    ? orderDetails.pickupFlatOrOfficeNumber || ""
                    : orderDetails.destinationFlatOrOfficeNumber || "",
                  remarks: orderDetails.deliveryInstructions || "",
                }
              : {
                  deliveryMobile: orderDetails.destinationMobileNumber || "",
                  altDeliveryMobile:
                    orderDetails.destinationAlternateNumber || "",
                  customerName: orderDetails.destinationCustomerName || "",
                  remarks: orderDetails.deliveryInstructions || "",
                  destination_address:
                    orderDetails?.destinationAddress ||
                    orderDetails?.senderAddress,
                };
          if (packageDisable === "true") {
            step2Data.orderFlowType = { id: 2, name: "Return" };
          }
          dispatch(saveStepData({ step: "step2", data: step2Data }));
          setEditData({ step1: step1Data, step2: step2Data });
        } else if (modeParam === "return_from_order") {
          const raw = localStorage.getItem("CREATE_ORDER_PREFILL");
          if (raw) {
            try {
              const parsed: any = JSON.parse(raw);
              const packages = Array.isArray(parsed?.selectedPackages)
                ? parsed.selectedPackages
                : [];
              const step1Data = {
                serviceType: createOrderData?.step1?.serviceType || null,
                orderFlowType: { id: 2, name: "Return" },
                packageCount: packages.length || 1,
                order_package_list: (packages.length
                  ? packages
                  : [
                      {
                        package_id: 1,
                        weight: 1,
                        package_description: allData?.packageDescription || "",
                        customer_input_package_value: 0,
                      },
                    ]
                ).map((pkg: any) => ({
                  package_id: pkg?.packageId ?? 1,
                  weight: pkg?.weight ?? 1,
                  package_description:
                    pkg?.packageDescription ||
                    allData?.packageDescription ||
                    "",
                  customer_input_package_value:
                    pkg?.customerInputPackageValue || 0,
                  external_package_id: pkg?.externalPackageId || "",
                })),
                totalWeight: (packages || []).reduce(
                  (sum: number, p: any) => sum + Number(p?.weight || 0),
                  0
                ),
                codDetails: { codEnabled: false, codAmount: "0.000" },
              };
              dispatch(saveStepData({ step: "step1", data: step1Data }));
              setIsEditMode(false);
              setStep(2);
            } catch {
              // ignore
            }
          }
        } else {
          setIsEditMode(false);
        }
        setCustomerName(customerNameParam || "");
      } catch (error) {
        console.error("Failed to fetch orders:", error);
      } finally {
        setIsLoading(false);
      }
    };
    fetchOrders();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams, dispatch, orderId, storedUser, mode]);

  const confirmSaveStep = (step: any, updatedData: any) => {
    const payloadData = {
      serviceType: updatedData?.serviceType,
      packageDetails: updatedData?.order_package_list,
      package_details: updatedData?.order_package_list,
      totalWeight: updatedData?.totalWeight ?? 0,
      codDetails: updatedData?.codDetails,
    };
    dispatch(saveStepData({ step: "step1", data: payloadData }));
  };

  return (
    <>
      {isLoading && <HourGlassLoader />}
      <div
        id="menu-wizard-step-1"
        className="menu menu-box-right bg-white sendPackageBox menu-active"
        data-menu-height="cover"
        data-menu-width="cover"
      >
        <div className="header header-logo-center header-active shadow-l">
          <Link href={process.env.NEXT_PUBLIC_MODE !== 'production' ? "/create-international-order" : ''} className="header-title">
            {isEditMode
              ? `Edit International Order${
                  customerName ? ` (${customerName})` : ""
                }`
              : "Create International Order"}
          </Link>
          <a href="/dashboard" className="header-icon header-icon-1">
            <i className="fas fa-chevron-left" />
          </a>{" "}
        </div>
        <div
          className="card card-style bg-transparent shadow-0 mb-0 mx-3"
          style={{ height: "100%" }}
        >
          <div className="card-top mt-70">
            <StepMenu step={step} setStep={setStep} />
            <div
              className="divider position-absolute tab-divider start-0 end-0 stepBorderBox"
              style={{ zIndex: -1, marginTop: "-37px" }}
            />
            {step === 1 && (
              <Step1
                onSave={(data) => handleSave("step1", data)}
                step={step}
                setStep={setStep}
                defaultOrderDetails={
                  (mode === "edit" || mode === "edit_order") &&
                  orderId &&
                  editData?.step1
                    ? editData?.step1
                    : defaultOrderDetails
                }
                isEditMode={isEditMode}
                confirmSaveStep={confirmSaveStep}
              />
            )}
            {step === 2 && (
              <Step2
                onSave={(data) => handleSave("step2", data)}
                step={step}
                setStep={setStep}
                defaultOrderDetails={defaultOrderDetails}
                isEditMode={isEditMode}
              />
            )}
            {step === 3 && (
              <Step3
                onSave={(data) => handleSave("step3", data)}
                step={step}
                setStep={setStep}
                defaultOrderDetails={defaultOrderDetails}
              />
            )}
            {step === 4 && (
              <Step4
                onSave={(data: any) => handleSave("step4", data)}
                step={step}
                setStep={setStep}
                defaultOrderDetails={defaultOrderDetails}
                isEditMode={isEditMode}
              />
            )}
          </div>
        </div>
      </div>
    </>
  );
}
