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

interface PropsType {
  tab?: any;
  edit?: boolean;
  page?: string;
  filters?: any;
  orderCardDetails?: any;
  setDashboard?: any;
  dashboard?: any;
  refreshList?: boolean;
  handleEdit: any;
  orders: any;
  setOrders: any;
  setRefreshList: any;
}

const OrderCard = ({
  orders,
  setOrders,
  tab = "draft",
  edit = true,
  page = "",
  filters,
  orderCardDetails,
  refreshList = false,
  setRefreshList,
  handleEdit
}: PropsType) => {
  const storedUser = localStorage.getItem("ALL_DATA");
  const allData = storedUser ? JSON.parse(storedUser)?.data : null;
  const [accordionView] = React.useState<boolean>(false);
  const [selectedOrders, setSelectedOrders] = React.useState<any>({});
  const [isLoading, setIsLoading] = React.useState<boolean>(true);
  const [customizeOrderModal, setCustomizeOrderModal] =
    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 };
      if (page === "dashboard-today_orders") {
        appliedFilters.limit = 4;
      }
      const orderList: any = await getBulkOrders(tab, appliedFilters);
      setOrders(orderList?.data?.data);
      setRefreshList(false)
      setIsLoading(false);
    } catch (error) {
      setIsLoading(false);
      console.error("Failed to fetch orders:", error);
    } finally {
      setIsLoading(false);
    }
  }, [filters, page, tab, setOrders, setRefreshList]);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleReturnOrder = async (orderDetail: any) => {
    try {
      toast.warning("Api not found");
      // const response = await createReturnOrder({ id: orderDetail.id });
      // if (response?.status) {
      //   toast.success("Return order created successfully");
      //   const newOrderId = response?.data?.id;
      //   if (newOrderId) {
      //     router.push(`/order-view?id=${cryptoHandler(newOrderId, "encrypt")}`);
      //   } else {
      //     toast.error("Could not get new return order ID");
      //   }
      // } else {
      //   toast.error(response?.message || "Failed to create return order");
      // }
    } catch (error: any) {
      toast.error(
        error?.response?.data?.message ||
        error?.message ||
        "Failed to create return order. Please try again."
      );
    }
  };
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleExchangeOrder = (orderDetail: any) => {
    toast.warning("Api not found");
  };
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleCancelOrder = (orderDetail: any) => {
    toast.warning("Api not found");
  };
  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, refreshList]);

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

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

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleFuturePickupFlag = async (orderId = 0, orderData: any) => {
    setIsLoading(true);
    try {
      const isMarked = await handleFuturePickup(orderId, orderData);
      if (isMarked) {
        await fetchOrders();
      }
    } catch (error) {
      console.error("Error in future pickup:", error);
    } finally {
      setIsLoading(false);
    }
  };
  return (
    <>
      <style>
        {`
          .dropdown-menu.show {    
            font-size: 12px;
            background: #f7deff;
            border-color: #dedbdb;
          }
        `}
      </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="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">
                  <div className="content">
                    <div className="maindiv">
                      <div className="w-100">
                        <div className="d-float-center justify-content-between mb-2"

                          ref={(el) => {
                            dropdownContainerRefs.current[order.id] = el;
                          }}
                        >
                          {(allData?.companyName || order?.pickupCustomerName) ? (
                            <h6 className="font-500 font-14 d-float-center mb-0">
                              {/* <Link
                                  href={`/group-order-view?id=${cryptoHandler(
                                          order?.id,
                                          "encrypt"
                                        )}`
                                  }
                                  data-menu="place-pickup-modal"
                                > */}
                              {truncateWithTooltip(allData?.companyName || order?.pickupCustomerName).text}{" "}
                              {/* </Link> */}
                            </h6>
                          ) : (
                            ""
                          )}
                          <div className="d-float-center box">
                            <span className={`badge ${getOrderStatusInfo(order?.status?.id, order)
                              ?.color
                              } rounded-xl font-12 px-2`}>
                              {
                                getOrderStatusInfo(order?.status?.id, order)
                                  ?.text
                              }
                            </span>
                          </div>
                          <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"
                              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(
                                    `/bulk-order-view?id=${cryptoHandler(
                                      order?.id,
                                      "encrypt"
                                    )}`
                                  );
                                }}
                              >
                                <i className="fa fa-eye" /> View
                              </button>
                              {(order?.status?.id === BulkOrderStatus.Created || order?.status?.id === BulkOrderStatus?.FileUploaded) ? (
                                <>
                                  <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 text-primary"></i>{" "}
                                    Edit
                                  </button>
                                </>
                              ) : order?.status?.id ===
                                OrderStatus.Delivered ? (
                                <>
                                  <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" }}
                                    onClick={(e) => {
                                      e.preventDefault();
                                      e.stopPropagation();
                                      handleExchangeOrder(order);
                                    }}
                                  >
                                    <i className="fa fa-retweet text-primary"></i>{" "}
                                    Create Exchange Order
                                  </button>
                                </>
                              ) : (
                                ""
                              )}
                            </div>
                          )}
                        </div>
                        <h6 className="font-400 font-13 opacity-60 mb-2">
                          <span className="box">
                            {order?.pickupMobileNumber ? (
                              <>
                                <i className="ri-phone-line position-unset mt-n2" />{" "}
                                {order?.pickupMobileNumber ? order?.pickupMobileNumber : ''}
                              </>
                            ) : ''}
                          </span>
                        </h6>
                        <h6 className="font-400 font-13 opacity-60 mb-2">
                          <span className="box">
                            <i className="ri-map-pin-line position-unset mt-n2" />{" "}
                            {allData?.addressFormatType?.name === "Standard" ? getFormattedAddress() : ""}
                            {/* {order?.pickupFlatOrOfficeNumber ? (
                              <>
                                <i className="ri-map-pin-line position-unset mt-n2" />{" "}
                                {order?.pickupFlatOrOfficeNumber ? truncateWithTooltip(order?.pickupFlatOrOfficeNumber).text : ''}
                              </>
                            ) : ''} */}
                          </span>
                        </h6>
                        <hr></hr>
                        <div className="order-info-icons d-float-center justify-content-between">
                          <div className="d-float-center gap-15">

                            <div className="d-float-center weight">
                              <i className="ri-calendar-line align-middle me-1" />
                              <h6 className="font-13 font-400 mb-0">
                                <span className="">
                                  {formatDate(order?.pickupDate || "")}
                                </span>{" "}
                              </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="">
                                  {parseFloat(order?.totalWeight || 0).toFixed(3)} 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?.totalCodAmount || 0
                                )}
                              </span>
                            </h6>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </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>
      {customizeOrderModal && (
        <BottomSheetModal
          show={customizeOrderModal}
          onHide={() => {
            setCustomizeOrderModal(false);
            setSelectedOrders({});
          }}
          header={false}
        >
          <CustomizeOrderModal orderDetails={selectedOrders} />
        </BottomSheetModal>
      )}
    </>
  );
};

export default OrderCard;
