/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import Image from "next/image";
import React, { useCallback } from "react";
import {
  createOrder,
  createReturnOrder,
  deleteDraft,
  getOrders,
  cancelOrder,
} from "../../../../Api/OrderApi";
import BottomSheetModal from "../../../Modal/BottomSheetModal";
import CustomizeOrderModal from "../../../Modal/CustomizeOrderModal";
import CreateReturnOrderModal from "../../../Modal/CreateReturnOrderModal";
import CancelOrderModal from "../../../Modal/CancelOrderModal";
import HourGlassLoader from "../../../Loader/Loader";
import Link from "next/link";
import {
  amountFormatWithCurrency,
  cryptoHandler,
  getFormattedAddress,
  getOrderStatusInfo,
  handleFuturePickup,
  truncateWithTooltip,
} from "../../../../lib/Helper";
import NoData from "../../../NoDataContainer/NoData";
import { OrderFlowType, OrderStatus } from "@/Constant/enums";
import { usePathname, useRouter } from "next/navigation";
import { toast } from "react-toastify";
import AccordionOrder from "./AccordionOrder";
import Modal from "../../../Modal/Modal";

interface PropsType {
  tab?: any;
  edit?: boolean;
  page?: string;
  filters?: any;
  orderCardDetails?: any;
  setDashboard?: any;
  dashboard?: any;
}

const OrderCard = ({
  tab = "draft",
  edit = true,
  page = "",
  filters,
  orderCardDetails,
  setDashboard,
  dashboard,
}: PropsType) => {
  const truncateCharLimit = 35;
  const pathname = usePathname();
  const storedUser = localStorage.getItem("ALL_DATA");
  const allData = storedUser ? JSON.parse(storedUser)?.data : null;
  const hasReturnFlowPermission = Array.isArray(allData?.order_flow_types)
    ? allData?.order_flow_types?.some(
        (flow: any) => flow?.id === OrderFlowType.Return
      )
    : allData?.order_flow_types?.id === OrderFlowType.Return;
  const [accordionView] = React.useState<boolean>(false);
  const [orders, setOrders] = React.useState<any[]>([]);
  const [selectedOrders, setSelectedOrders] = React.useState<any>({});
  const [isLoading, setIsLoading] = React.useState<boolean>(true);
  const [customizeOrderModal, setCustomizeOrderModal] =
    React.useState<boolean>(false);
  const [returnOrderModal, setReturnOrderModal] =
    React.useState<boolean>(false);
  const [cancelOrderModal, setCancelOrderModal] =
    React.useState<boolean>(false);
  const [showDropdown, setShowDropdown] = React.useState<string | null>(null);
  const dropdownContainerRefs = React.useRef<
    Record<string, HTMLDivElement | null>
  >({});
  const router = useRouter();

  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const isClickInside = Object.values(dropdownContainerRefs.current).some(
        (ref) => ref && ref.contains(event.target as Node)
      );
      if (!isClickInside) {
        setShowDropdown(null);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);
  const fetchOrders = useCallback(async () => {
    try {
      setIsLoading(true);
      const appliedFilters: any = { ...filters };

      // Map filter fields to API expected format
      if (filters?.serviceTypes?.id) {
        appliedFilters.service_type_id = filters.serviceTypes.id;
      }
      if (filters?.orderFlowType?.id) {
        appliedFilters.order_flow_type_id = filters.orderFlowType.id;
      }
      if (filters?.orderId) {
        appliedFilters.order_id = filters.orderId;
      }
      if (filters?.customerOrderId) {
        appliedFilters.customer_order_id = filters.customerOrderId;
      }
      if (filters?.deliveryMobile) {
        appliedFilters.delivery_mobile = filters.deliveryMobile;
      }
      if (filters?.orderStatus?.id) {
        appliedFilters.order_status_id = filters.orderStatus.id;
      }
      if (filters?.packageId) {
        appliedFilters.package_id = filters.packageId;
      }
      if (filters?.noOfPackages) {
        appliedFilters.no_of_packages = filters.noOfPackages;
      }
      if (filters?.packageWeight) {
        appliedFilters.package_weight = filters.packageWeight;
      }
      if (filters?.packageValue) {
        appliedFilters.package_value = filters.packageValue;
      }
      if (filters?.packageStatus?.id) {
        appliedFilters.package_status_id = filters.packageStatus.id;
      }
      if (filters?.blockNumber?.id) {
        appliedFilters.block_id = filters.blockNumber.id;
      }
      if (filters?.roadNumber?.id) {
        appliedFilters.road_id = filters.roadNumber.id;
      }
      if (filters?.buildingNumber?.id) {
        appliedFilters.building_id = filters.buildingNumber.id;
      }
      if (filters?.flatNumber) {
        appliedFilters.flat_number = filters.flatNumber;
      }

      if (page === "dashboard-today_orders") {
        appliedFilters.limit = 4;
      }

      const orderList = await getOrders(tab, appliedFilters);
      const orderListAllResponse: any = await getOrders(
        tab,
        appliedFilters,
        true
      );
      if (tab === "in_progress")
        setDashboard({
          ...dashboard,
          in_progress_orders: orderListAllResponse?.data?.length || 0,
        });
      setOrders(orderList);
      setIsLoading(false);
    } catch (error) {
      setIsLoading(false);
      console.error("Failed to fetch orders:", error);
    } finally {
      setIsLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters, tab, page]);
  const handleEdit = (orderDetail: any) => {
    const url = `/create-order?mode=edit_order&orderId=${
      orderDetail?.id
    }&customerName=${encodeURIComponent(
      orderDetail?.destinationCustomerName || ""
    )}`;
    router.push(url);
  };
  const handleReturnOrder = async (orderDetail: any) => {
    setSelectedOrders(orderDetail);
    setReturnOrderModal(true);
  };
  const handleReturnSelectionConfirm = async (selectedPackages: any[]) => {
    try {
      setIsLoading(true);

      // Step 1 Payload
      const step1Payload = {
        step: 1,
        order_type: selectedOrders?.orderType?.id ?? 1,
        order_flow_type: { id: OrderFlowType.Return },
        package_details: selectedPackages, // use selectedPackages
        service_type: selectedOrders?.service_type_details,
        cod_details: {
          cod_enabled: selectedOrders?.isCod ?? false,
          cod_amount: selectedOrders?.codAmount ?? 0,
        },
      };

      // Call Step 1 API
      const step1Response = await createOrder(step1Payload, 0, null);
      if (!step1Response?.status) throw new Error("Step 1 failed");

      const draftOrderId =
        step1Response?.data?.id ||
        step1Response?.data?.orderId ||
        step1Response?.data?.customerInputOrderId;

      // Step 2 Payload (customer/destination details from selectedOrders)
      const step2Payload = {
        step: 2,
        // orderId: draftOrderId,
        order_id: selectedOrders?.customerInputOrderId || "",
        customer_name: selectedOrders?.destinationCustomerName || "",
        delivery_mobile: selectedOrders?.destinationMobileNumber || "",
        alt_delivery_mobile: selectedOrders?.destinationAlternateNumber || "",
        block_no:
          selectedOrders?.destination_block_details?.id === 1
            ? 0
            : selectedOrders?.destination_block_details || "",
        road_no:
          selectedOrders?.destination_road_details?.id === 1
            ? 0
            : selectedOrders?.destination_road_details || "",
        building_no:
          selectedOrders?.destination_building_details?.id === 1
            ? 0
            : selectedOrders?.destination_building_details || "",
        flat_no: selectedOrders?.destinationFlatOrOfficeNumber,
        sender_address: selectedOrders?.destinationAddress || "",
        delivery_instructions: selectedOrders?.deliveryInstructions || "",
        destination_address: selectedOrders?.senderAddress || "",
        // destination_customer_name: selectedOrders?.pickupCustomerName,
        // destination_mobile_number: selectedOrders?.pickupMobileNumber,
        // destination_alternate_number: selectedOrders?.pickupAlternateNumber,
        // destination_block_id: selectedOrders?.pickup_block_details?.id || "",
        // destination_road_id: selectedOrders?.pickup_road_details?.name || "",
        // destination_building_id: selectedOrders?.pickup_building_details?.name || "",
        // destination_flat_or_office_number: selectedOrders?.pickupFlatOrOfficeNumber || "",
      };

      const step2Response = await createOrder(
        step2Payload,
        0,
        { ...step1Response?.data, orderId: draftOrderId },
        draftOrderId,
        {
          step1: {
            ...step1Payload,
            orderFlowType: {
              id: OrderFlowType.Return,
              name: "Return",
            },
          },
        }
      );
      if (!step2Response?.status) throw new Error("Step 2 failed");
      // Step 3 Payload (final accept)
      const step3Payload = {
        step: 3,
        draft_order_id: draftOrderId,
        ref_order_id: selectedOrders?.id,
      };

      const step3Response = await createOrder(
        step3Payload,
        0,
        { orderId: draftOrderId, refOrderId: selectedOrders?.id || 0 },
        draftOrderId,
        { step1: step1Payload, step2: step2Payload }
      );
      if (!step3Response?.status) throw new Error("Step 3 failed");

      // ✅ All steps successful → redirect
      setReturnOrderModal(false);
      setShowDropdown(null);
      router.push(
        `/create-order?mode=edit&orderId=${draftOrderId}&customerName=${encodeURIComponent(
          selectedOrders?.pickupCustomerName
        )}&packageDisable=true`
      );
      router.refresh();
    } catch (err: any) {
      console.error("Failed to create return order:", err);
      setReturnOrderModal(false);
      toast.error("Failed to create return order. Please try again.");
    } finally {
      setIsLoading(false);
    }
  };

  const handleExchangeOrder = (orderDetail: any) => {
    toast.warning("Api not found");
  };
  const handleCancelOrder = (orderDetail: any) => {
    setSelectedOrders(orderDetail);
    setCancelOrderModal(true);
  };

  const handleCancelConfirm = async (reason: string) => {
    try {
      setIsLoading(true);
      const response = await cancelOrder(selectedOrders?.id, reason);
      if (response) {
        toast.success("Order cancelled successfully");
        setCancelOrderModal(false);
        setSelectedOrders({});
        setShowDropdown(null);
        router.push("/my-orders?_=cancel");
        fetchOrders();
      }
    } catch (error) {
      console.error("Error cancelling order:", error);
      toast.error("Failed to cancel order");
    } finally {
      setIsLoading(false);
    }
  };
  const handleTrackNow = (orderDetail: any) => {
    const url = `/order-tracking?id=${encodeURIComponent(
      orderDetail?.id || ""
    )}`;
    router.push(url);
  };
  // const handleDraftList= () => {
  //   const url = `/create-order?_=draft`;
  //   window.location.href = url;
  // };
  const handleDelete = async (orderDetail: any) => {
    try {
      await deleteDraft(orderDetail?.id);
      setShowDropdown(null);
      fetchOrders();
    } catch (error) {
      console.error("Error deleting draft:", error);
    }
  };
  const toggleDropdown = (orderId: string) => {
    setShowDropdown(showDropdown === orderId ? null : orderId);
  };

  React.useEffect(() => {
    fetchOrders();
  }, [fetchOrders, filters, tab]);

  if (isLoading) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "50vh",
        }}
      >
        <HourGlassLoader />
      </div>
    );
  }

  const handleEditOrder = (item: any) => {
    setSelectedOrders(item);
  };

  const handleFuturePickupFlag = async (orderId = 0, orderData: any) => {
    try {
      const isMarked = await handleFuturePickup(orderId, orderData);
      if (isMarked) {
        await fetchOrders();
      }
    } catch (error) {
      console.error("Error in future pickup:", error);
    }
  };
  return (
    <>
      <style>
        {`
          .dropdown-menu.show {    
            font-size: 12px;
            background: #f7deff;
            border-color: #dedbdb;
          }
          .order-list-section {
            height: 76vh;
            overflow: hidden;
            overflow-y: auto;
          }
          .bg-marked {
            background-color: #f6f6d9;
          }
          .bg-return {
            background-color: #f1e4e4ad
          }
          .dropdown-complete {
            top: -10px;
            right: 10px !important
          }
        `}
      </style>

      {isLoading && <HourGlassLoader />}
      {page ? (
        <>
          {page === "dashboard-draft_orders" ? (
            <>
              {orders?.length > 0 && (
                <div className="col-lg-12 my-orders-box">
                  <div className="d-float-center justify-content-between">
                    <h5 className="font-15 pb-1">
                      Draft Orders ({orders?.length || 0})
                    </h5>
                    {/* <Link href="/my-orders" className="font-700">
                      View all <i className="fa fa-long-arrow-right"></i>
                    </Link> */}
                  </div>
                </div>
              )}
            </>
          ) : page === "dashboard-today_orders" ? (
            <>
              {orders?.length > 0 && (
                <div className="col-lg-12 my-orders-box">
                  <div className="d-float-center justify-content-between">
                    <h5 className="font-15 pb-1">
                      Order Placed Today (
                      {orderCardDetails?.orders_placed_today || 0})
                    </h5>
                    {/* <Link href="/my-orders?_=in_progress" className="font-700">
                      View all <i className="fa fa-long-arrow-right"></i>
                    </Link> */}
                  </div>
                </div>
              )}
            </>
          ) : page === "dashboard-live_orders" ? (
            <>
              {orders?.length > 0 && (
                <div className="col-lg-12 my-orders-box">
                  <div className="d-float-center justify-content-between">
                    <h5 className="font-15 pb-1">
                      Live Orders ({orderCardDetails?.live_orders || 0})
                    </h5>
                    {/* <Link href="/my-orders?_=in_progress" className="font-700">
                      View all <i className="fa fa-long-arrow-right"></i>
                    </Link> */}
                  </div>
                </div>
              )}
            </>
          ) : (
            ""
          )}
        </>
      ) : (
        <></>
      )}
      <div
        className={`${pathname === "/my-orders" ? "order-list-section" : ""}`}
      >
        <div className="row px-0 mx-0 mb-0 draft-orders-row">
          {orders?.length > 0 ? (
            orders?.map((order: any, index: number) => (
              <div key={index} className="col-lg-3 order-list-box">
                {accordionView ? (
                  <AccordionOrder
                    index={index}
                    order={order}
                    page={page}
                    tab={tab}
                    dropdownContainerRefs={dropdownContainerRefs}
                    edit={edit}
                    showDropdown={showDropdown}
                    toggleDropdown={toggleDropdown}
                    handleEdit={handleEdit}
                    handleDelete={handleDelete}
                    setCustomizeOrderModal={setCustomizeOrderModal}
                    handleEditOrder={handleEditOrder}
                    handleTrackNow={handleTrackNow}
                    handleCancelOrder={handleCancelOrder}
                    handleReturnOrder={handleReturnOrder}
                    handleExchangeOrder={handleExchangeOrder}
                    allData={allData}
                  />
                ) : (
                  <div
                    className={`card card-style mb-3 mx-0 ${
                      tab === "fixed-height" ? "order-list-heightSame" : ""
                    } ${
                      order?.isFuturePickup && tab === "draft"
                        ? "bg-marked"
                        : ""
                    } ${
                      order?.orderFlowType?.id === OrderFlowType.Return &&
                      tab !== "draft"
                        ? "bg-return"
                        : ""
                    }`}
                  >
                    <div className="content">
                      <div className="maindiv">
                        <div className="w-100">
                          <div
                            className="position-relative d-float-center justify-between mb-2"
                            ref={(el) => {
                              dropdownContainerRefs.current[order.id] = el;
                            }}
                          >
                            {tab === "draft" ? (
                              <>
                                {!edit ? (
                                  <>
                                    <span className="badge delybell-yellow rounded-xl font-12 px-2">
                                      Pending
                                    </span>
                                    {order?.orderFlowType?.id ===
                                    OrderFlowType.Return ? (
                                      <span
                                        className={`badge bg-purple rounded-xl font-12 px-2`}
                                      >
                                        <i
                                          className={`ri ri-arrow-go-back-line`}
                                        />{" "}
                                        {order?.orderFlowType?.name}
                                      </span>
                                    ) : (
                                      ""
                                    )}
                                    {order?.isFuturePickup ? (
                                      <>
                                        {" "}
                                        &nbsp;
                                        <i className="ri ri-timer-line font-18"></i>
                                      </>
                                    ) : (
                                      ""
                                    )}
                                    <a
                                      href="#"
                                      onClick={(e) => {
                                        e.preventDefault();
                                        toggleDropdown(order.id);
                                      }}
                                      className="ms-auto"
                                    >
                                      <i className="fa icon-30 text-end fa fa-ellipsis-v font-12 color-primary" />
                                    </a>
                                    {showDropdown === order.id && (
                                      <div
                                        className="dropdown-menu show position-absolute end-0 mt-2 dropdown-complete"
                                        style={{
                                          zIndex: 9999,
                                          right: 0,
                                          minWidth: "120px",
                                        }}
                                        onClick={(e) => e.stopPropagation()}
                                      >
                                        {order?.refOrderId ? (
                                          ""
                                        ) : (
                                          <button
                                            type="button"
                                            className="dropdown-item d-flex align-items-center gap-2"
                                            style={{ cursor: "pointer" }}
                                            onClick={(e) => {
                                              e.preventDefault();
                                              e.stopPropagation();
                                              handleEdit(order);
                                            }}
                                          >
                                            <i className="fa fa-edit"></i> Edit
                                          </button>
                                        )}
                                        {/* <button
                                            type="button"
                                            className="dropdown-item d-flex align-items-center gap-2"
                                            style={{ cursor: "pointer" }}
                                            onClick={(e) => {
                                              e.preventDefault();
                                              e.stopPropagation();
                                              handleDraftList();
                                            }}
                                          >
                                            <i className="fa fa-eye"></i>{" "}
                                            Draft Orders
                                          </button> */}
                                        <button
                                          className="dropdown-item d-flex align-items-center gap-2"
                                          onClick={() => handleDelete(order)}
                                        >
                                          <i className="fa fa-trash"></i> Delete
                                        </button>
                                        {order?.isFuturePickup ? (
                                          <button
                                            className="dropdown-item d-flex align-items-center gap-2"
                                            onClick={() =>
                                              handleFuturePickupFlag(
                                                order?.id,
                                                order
                                              )
                                            }
                                          >
                                            <i className="fa fa-clock"></i>{" "}
                                            Unmark Future Pickup
                                          </button>
                                        ) : (
                                          <button
                                            className="dropdown-item d-flex align-items-center gap-2"
                                            onClick={() =>
                                              handleFuturePickupFlag(
                                                order?.id,
                                                order
                                              )
                                            }
                                          >
                                            <i className="fa fa-clock"></i> Mark
                                            as Future Pickup
                                          </button>
                                        )}
                                      </div>
                                    )}
                                  </>
                                ) : (
                                  <a
                                    data-menu="order-quick-edit"
                                    className="float-end"
                                    href="#"
                                    onClick={() => {
                                      setCustomizeOrderModal(true);
                                      handleEditOrder(order);
                                    }}
                                  >
                                    <i className="fa icon-30 text-end fa-edit font-14 color-primary" />
                                  </a>
                                )}
                              </>
                            ) : (
                              <>
                                <span
                                  className={`badge ${
                                    getOrderStatusInfo(order?.status?.id, order)
                                      ?.color
                                  } rounded-xl font-12 px-2`}
                                >
                                  {
                                    getOrderStatusInfo(order?.status?.id, order)
                                      ?.text
                                  }
                                </span>
                                {order?.orderFlowType?.id ===
                                OrderFlowType.Return ? (
                                  <span
                                    className={`badge bg-purple rounded-xl font-12 px-2`}
                                  >
                                    <i className={`ri ri-arrow-go-back-line`} />{" "}
                                    {order?.orderFlowType?.name}
                                  </span>
                                ) : (
                                  ""
                                )}
                                {/* {order?.orderFlowType?.id === OrderFlowType.Return ? (
                                <>
                                  {" "}&nbsp;<i className="ri ri-loop-left-line font-18"></i>
                                </>
                              ) : ''} */}
                                {order?.status?.id !== OrderStatus.Cancelled ? (
                                  <a
                                    href="#"
                                    onClick={(e) => {
                                      e.preventDefault();
                                      toggleDropdown(order.id);
                                    }}
                                    className="ms-auto"
                                  >
                                    <i className="fa icon-30 text-end fa fa-ellipsis-v font-12 color-primary" />
                                  </a>
                                ) : (
                                  ""
                                )}
                                {showDropdown === order.id && (
                                  <div
                                    className="dropdown-menu show position-absolute end-0 mt-2 dropdown-complete"
                                    style={{
                                      zIndex: 9999,
                                      right: 0,
                                      minWidth: "120px",
                                    }}
                                    onClick={(e) => e.stopPropagation()}
                                  >
                                    <button
                                      type="button"
                                      className="dropdown-item d-flex align-items-center gap-2"
                                      style={{ cursor: "pointer" }}
                                      onClick={(e) => {
                                        e.preventDefault();
                                        e.stopPropagation();
                                        router.push(
                                          `/order-view?id=${cryptoHandler(
                                            order?.id,
                                            "encrypt"
                                          )}`
                                        );
                                      }}
                                    >
                                      <i className="fa fa-eye" /> View
                                    </button>
                                    <button
                                      type="button"
                                      className="dropdown-item d-flex align-items-center gap-2"
                                      style={{ cursor: "pointer" }}
                                      onClick={(e) => {
                                        e.preventDefault();
                                        e.stopPropagation();
                                        handleTrackNow(order);
                                      }}
                                    >
                                      <i className="fa fa-map me-1" /> Track Now
                                    </button>
                                    {order?.status?.id === OrderStatus.Open ||
                                    order?.status?.id ===
                                      OrderStatus.PendingPickup ? (
                                      <>
                                        <button
                                          type="button"
                                          className="dropdown-item d-flex align-items-center gap-2"
                                          style={{ cursor: "pointer" }}
                                          onClick={(e) => {
                                            e.preventDefault();
                                            e.stopPropagation();
                                            handleCancelOrder(order);
                                          }}
                                        >
                                          <i className="fa fa-ban text-primary"></i>{" "}
                                          Cancel
                                        </button>
                                      </>
                                    ) : (
                                      <></>
                                    )}
                                    {(order?.status?.id ===
                                      OrderStatus.Delivered ||
                                      order?.status?.id ===
                                        OrderStatus.Exception) &&
                                    !order?.isReturnGenerated &&
                                    order?.orderFlowType?.id ===
                                      OrderFlowType.Forward &&
                                    hasReturnFlowPermission ? (
                                      <>
                                        <button
                                          type="button"
                                          className="dropdown-item d-flex align-items-center gap-2"
                                          style={{ cursor: "pointer" }}
                                          onClick={(e) => {
                                            e.preventDefault();
                                            e.stopPropagation();
                                            handleReturnOrder(order);
                                          }}
                                        >
                                          <i className="fa fa-rotate-left text-primary"></i>{" "}
                                          Create Return Order
                                        </button>
                                        <button
                                          type="button"
                                          className="dropdown-item d-flex align-items-center gap-2"
                                          style={{ cursor: "pointer" }}
                                          disabled
                                          onClick={(e) => {
                                            e.preventDefault();
                                            e.stopPropagation();
                                            handleExchangeOrder(order);
                                          }}
                                        >
                                          <i className="fa fa-retweet text-primary"></i>{" "}
                                          Create Exchange Order
                                        </button>
                                      </>
                                    ) : (
                                      ""
                                    )}
                                  </div>
                                )}
                              </>
                            )}
                          </div>
                          <div className="d-float-center justify-content-between mb-2">
                            {order?.customerInputOrderId ||
                            truncateWithTooltip(
                              order?.destinationCustomerName,
                              truncateCharLimit
                            ).text ||
                            order?.generatedOrderId ? (
                              <h6 className="font-500 font-14 d-float-center mb-0">
                                {page === "dashboard-draft_orders" ||
                                tab === "draft" ? (
                                  <span
                                    className="font-700 font-15 text-dark"
                                    title={
                                      page === "dashboard-draft_orders" ||
                                      tab === "draft"
                                        ? order?.customerInputOrderId ||
                                          truncateWithTooltip(
                                            order?.destinationCustomerName,
                                            truncateCharLimit
                                          )?.tooltip
                                        : order?.generatedOrderId
                                    }
                                  >
                                    {" "}
                                    {page === "dashboard-draft_orders" ||
                                    tab === "draft"
                                      ? order?.customerInputOrderId ||
                                        truncateWithTooltip(
                                          order?.destinationCustomerName,
                                          truncateCharLimit
                                        ).text
                                      : order?.generatedOrderId}{" "}
                                  </span>
                                ) : (
                                  <Link
                                    href={
                                      page === "dashboard-draft_orders" ||
                                      tab === "draft"
                                        ? `/create-order?_=draft`
                                        : `/order-view?id=${cryptoHandler(
                                            order?.id,
                                            "encrypt"
                                          )}`
                                    }
                                    data-menu="place-pickup-modal"
                                    title={
                                      page === "dashboard-draft_orders" ||
                                      tab === "draft" ||
                                      page === "dashboard-live_orders"
                                        ? order?.customerInputOrderId ||
                                          truncateWithTooltip(
                                            order?.destinationCustomerName,
                                            truncateCharLimit
                                          )?.tooltip
                                        : order?.generatedOrderId
                                    }
                                  >
                                    {page === "dashboard-draft_orders" ||
                                    tab === "draft" ||
                                    page === "dashboard-live_orders"
                                      ? order?.customerInputOrderId ||
                                        truncateWithTooltip(
                                          order?.destinationCustomerName,
                                          truncateCharLimit
                                        ).text
                                      : order?.generatedOrderId}{" "}
                                    {/* Using optional chaining */}
                                  </Link>
                                )}
                                {/* {order?.customerInputOrderId &&
                              order?.destinationCustomerName
                                ? " - "
                                : ""}{" "} */}
                              </h6>
                            ) : (
                              ""
                            )}
                            <p className="mb-0 font-13 font-400">
                              <span className="badge card-status rounded-xl font-12 px-2">
                                {order?.service_type_details?.name}{" "}
                              </span>
                            </p>
                          </div>
                          {/* {page == "dashboard-draft_orders" ||
                              tab === "draft"  ? '' : (
                          <Link href="#" className="font-500 font-14 mb-2">
                            <span className="font-700 font-15 text-dark" title={page === "dashboard-draft_orders" ||
                              tab === "draft"
                                ? order?.customerInputOrderId
                                  ? order?.customerInputOrderId
                                  : ""
                                : truncateWithTooltip(order?.destinationCustomerName, truncateCharLimit)?.tooltip}>
                              {
                              page === "dashboard-draft_orders" ||
                              tab === "draft"
                                ? (order?.destinationCustomerName && order?.customerInputOrderId)
                                  ? truncateWithTooltip(order?.destinationCustomerName, truncateCharLimit).text
                                  : ""
                                :
                                 truncateWithTooltip(order?.destinationCustomerName, truncateCharLimit).text}{" "}
                            </span>
                          </Link>
                              )} */}
                          <h6 className="font-400 font-13 opacity-60 mb-2">
                            <span
                              className="box"
                              title={
                                allData?.addressFormatType?.name !== "Standard"
                                  ? order?.orderFlowType?.id ===
                                    OrderFlowType.Return
                                    ? order?.senderAddress
                                    : order?.destinationAddress
                                  : order?.orderFlowType?.id ===
                                    OrderFlowType.Return
                                  ? getFormattedAddress(
                                      order,
                                      "order_summary_return"
                                    )
                                  : getFormattedAddress(order, "order_summary")
                              }
                            >
                              {/* <i className="ri-map-pin-line position-unset mt-n2" />{" "} */}
                              {(() => {
                                const rawAddress =
                                  allData?.addressFormatType?.name !==
                                  "Standard"
                                    ? order?.orderFlowType?.id ===
                                      OrderFlowType.Return
                                      ? order?.senderAddress
                                      : order?.destinationAddress
                                    : order?.orderFlowType?.id ===
                                      OrderFlowType.Return
                                    ? getFormattedAddress(
                                        order,
                                        "order_summary_return"
                                      )
                                    : getFormattedAddress(
                                        order,
                                        "order_summary"
                                      );

                                const truncated = truncateWithTooltip(
                                  rawAddress,
                                  50
                                ); // pick your char limit
                                return (
                                  <>
                                    <i className="ri-map-pin-line position-unset mt-n2" />{" "}
                                    {truncated?.text ?? "Not Available"}
                                  </>
                                );
                              })()}
                            </span>
                          </h6>
                          <hr></hr>
                          <div className="order-info-icons d-float-center justify-content-between">
                            <div className="d-float-center gap-15">
                              {/* <p className="mb-0 font-13 font-400">
                                <span className="badge card-status rounded-xl font-12 px-2">
                                  {order?.service_type_details?.name}{" "}
                                </span>
                              </p> */}
                              <div className="d-float-center box">
                                <Image
                                  className="order-icons img-fluid"
                                  src="/images/icons/box.svg"
                                  alt="Box Icon"
                                  width={32}
                                  height={32}
                                />
                                <h6 className="font-13 font-400 mb-0">
                                  <span className="">
                                    {order?.order_package_list?.length ||
                                      order?.draft_order_package_list?.length ||
                                      0}{" "}
                                    Pkgs
                                  </span>{" "}
                                  {/* Using optional chaining */}
                                </h6>
                              </div>
                              <div className="d-float-center weight">
                                <Image
                                  className="order-icons img-fluid"
                                  src="/images/icons/weight.svg"
                                  alt="Weight Icon"
                                  width={32}
                                  height={32}
                                />
                                <h6 className="font-13 font-400 mb-0">
                                  <span className="">
                                    {order?.totalWeight} KG
                                  </span>{" "}
                                  {/* Using optional chaining */}
                                </h6>
                              </div>
                            </div>
                            <div className="d-float-center wallet">
                              <Image
                                className="order-icons img-fluid"
                                src="/images/icons/wallet.svg"
                                alt="Wallet Icon"
                                width={32}
                                height={32}
                              />
                              <h6 className="font-13 font-700 mb-0">
                                <span className="color-red-dark">
                                  {amountFormatWithCurrency(
                                    order?.calculatedTotalShippingCharge || 0
                                  )}
                                </span>
                              </h6>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
                {/* <a className="font-700" href="/my-orders">View all <i className="fa fa-long-arrow-right"></i></a> */}
              </div>
            ))
          ) : (
            <>
              {page === "dashboard-today_orders" ||
              page === "dashboard-draft_orders" ||
              page === "dashboard-live_orders" ? (
                ""
              ) : (
                <NoData />
              )}
            </>
          )}
          {orders?.length > 0 &&
          (page === "dashboard-today_orders" ||
            page === "dashboard-draft_orders") ? (
            <a
              className="font-700 text-center mb-4"
              href={`${
                page === "dashboard-today_orders"
                  ? "/my-orders?_=in_progress"
                  : "/my-orders"
              }`}
            >
              View all <i className="fa fa-long-arrow-right"></i>
            </a>
          ) : null}
        </div>
      </div>
      {customizeOrderModal && (
        <BottomSheetModal
          show={customizeOrderModal}
          onHide={() => {
            setCustomizeOrderModal(false);
            setSelectedOrders({});
          }}
          header={false}
        >
          <CustomizeOrderModal orderDetails={selectedOrders} />
        </BottomSheetModal>
      )}
      {returnOrderModal && (
        <Modal
          show={returnOrderModal}
          onHide={() => {
            setReturnOrderModal(false);
            setSelectedOrders({});
          }}
          header={false}
          title=""
          fullscreen={"xl"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >
          <CreateReturnOrderModal
            orderDetails={selectedOrders}
            onCancel={() => {
              setReturnOrderModal(false);
              setSelectedOrders({});
            }}
            onConfirm={handleReturnSelectionConfirm}
          />
        </Modal>
      )}
      {cancelOrderModal && (
        <Modal
          show={cancelOrderModal}
          onHide={() => {
            setCancelOrderModal(false);
            setSelectedOrders({});
          }}
          header={false}
          title=""
          fullscreen={"xl"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >
          <CancelOrderModal
            orderId={selectedOrders?.generatedOrderId || selectedOrders?.id}
            onCancel={() => {
              setCancelOrderModal(false);
              setSelectedOrders({});
            }}
            onConfirm={handleCancelConfirm}
          />
        </Modal>
      )}
    </>
  );
};

export default OrderCard;
