"use client";

/* eslint-disable @typescript-eslint/no-explicit-any */
import Image from "next/image";
import BottomSheetModal from "../../../../Modal/BottomSheetModal";
import React, { useRef, useState } from "react";
import CustomizeOrderModal from "../../../../Modal/CustomizeOrderModal";
import { deleteDraft } from "../../../../../Api/OrderApi";
import { useRouter } from "next/navigation";
import {
  amountFormatWithCurrency,
  truncateWithTooltip,
} from "../../../../../lib/Helper";
import { OrderFlowType } from "@/Constant/enums";

type OrderCardProps = any;

const OrderCard: React.FC<OrderCardProps> = ({
  customerInputOrderId,
  address = "",
  totalWeight,
  destinationCustomerName,
  service_type_details,
  numberOfPackages,
  calculatedTotalShippingCharge,
  orderDetail,
  fetchOrders,
  handleFuturePickupFlag,
}) => {
  const router = useRouter();
  const [customizeOrderModal, setCustomizeOrderModal] =
    useState<boolean>(false);
  const [showDropdown, setShowDropdown] = useState<boolean>(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const toggle = () => setCustomizeOrderModal(!customizeOrderModal);
  const handleChange = () => {
    toggle();
  };

  const handleEdit = () => {
    setShowDropdown(false);
    // Navigate to create order page with order ID
    // dispatch(resetOrderData())
    router.push(
      `/create-order?mode=edit&orderId=${
        orderDetail?.id
      }&customerName=${encodeURIComponent(destinationCustomerName)}${orderDetail?.refOrderId ? "&packageDisable=true" : ""}`
    );
    window.location.href = `/create-order?mode=edit&orderId=${
        orderDetail?.id
      }&customerName=${encodeURIComponent(destinationCustomerName)}${orderDetail?.refOrderId ? "&packageDisable=true" : ""}`;
    router.refresh();
  };

  const handleDelete = async (id: any) => {
    try {
      await deleteDraft(id);
      setShowDropdown(false);
      fetchOrders();
    } catch (error) {
      console.error("Error deleting draft:", error);
    }
  };

  // Close dropdown when clicking outside
  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setShowDropdown(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);
  return (
    <>
      <style>
        {`
          .sendPackageBox .scrollWrap { height: 81vh; }
          .bg-marked {
            background-color: #f6f6d9;
          }
        `}
      </style>
      <div className="col-lg-3 order-list-box">
        <div className={`card card-style mb-4 order-list-heightSame ${orderDetail?.isFuturePickup ? 'bg-marked' : ''}`}>
          <div className="content">
            <div className="maindiv">
              <div className="w-100">
                <div className="d-float-center justify-content-between">
                  <div className="d-float-center">
                    <h6 className="font-500 font-14 mb-2 d-float-center">
                      <a href="#" data-menu="place-pickup-modal">
                        {customerInputOrderId}
                      </a>{" "}
                    </h6>
                    <p className="mb-2 font-13 font-400">
                      <span className="badge card-status rounded-xl font-12 px-2">
                        {service_type_details?.name}
                      </span>
                      {orderDetail?.orderFlowType?.id === OrderFlowType.Return ? (
                        <span className="badge bg-purple rounded-xl font-12 px-2">
                          <i className={`ri ri-arrow-go-back-line`} />{" "}
                          {orderDetail?.orderFlowType?.name}
                        </span>
                      ) : ''}
                      {orderDetail?.isFuturePickup ? (
                        <>
                          {" "}&nbsp;<i className="ri ri-timer-line font-18"></i>
                        </>
                      ) : ''}
                    </p>
                  </div>
                  <div className="position-relative">
                    <a
                      href="#"
                      onClick={(e) => {
                        e.preventDefault();
                        setShowDropdown(!showDropdown);
                      }}
                    >
                      <i className="fa icon-30 text-end fa fa-ellipsis-v font-12 color-primary" />
                    </a>
                    {showDropdown && (
                      <div
                        ref={dropdownRef}
                        className="dropdown-menu show position-absolute end-0 mt-2"
                        style={{ zIndex: 9999 }}
                      >
                        {/* {orderDetail?.refOrderId ? "" : ( */}
                          <button
                            className="dropdown-item d-flex align-items-center gap-2"
                            onClick={handleEdit}
                          >
                            <i className="fa fa-edit"></i> Edit
                          </button>
                        {/* // )} */}
                        <button
                          className="dropdown-item d-flex align-items-center gap-2"
                          onClick={() => handleDelete(orderDetail?.id)}
                        >
                          <i className="fa fa-trash"></i> Delete
                        </button>
                        {orderDetail?.isFuturePickup ? (
                          <button
                            className="dropdown-item d-flex align-items-center gap-2"
                            onClick={() =>
                              handleFuturePickupFlag(orderDetail?.id, orderDetail)
                            }
                          >
                            <i className="fa fa-clock"></i> Unmark Future Pickup
                          </button>
                        ) : (
                          <button
                            className="dropdown-item d-flex align-items-center gap-2"
                            onClick={() =>
                              handleFuturePickupFlag(orderDetail?.id, orderDetail)
                            }
                          >
                            <i className="fa fa-clock"></i> Mark as Future
                            Pickup
                          </button>
                        )}
                      </div>
                    )}
                  </div>
                </div>
                <h6 className="font-500 font-14 mb-2 d-float-center">
                  <span className="font-700 font-15 text-dark" title={destinationCustomerName || ""}>
                          {truncateWithTooltip(destinationCustomerName, 45).text}
                  </span>
                </h6>
                <h6 className="font-400 font-13 opacity-50 mb-2">
                  <p className="mb-2 font-13 font-400">
                    {/* <span className="badge badge-purple2  rounded-xl font-12 px-2">
                      {orderDetail?.isFuturePickup
                        ? "Marked as Future Pickup"
                        : ""}
                    </span> */}
                  </p>
                  <span title={truncateWithTooltip(address || "", 35)?.text}>
                    <i className="ri-map-pin-line position-unset mt-n2" /> {" "}
                    {truncateWithTooltip(address || "", 53)?.text}
                  </span>
                </h6>
                <div className="order-info-icons d-float-center justify-content-between">
                  <div className="d-float-center gap-15">
                    <div className="d-float-center box">
                      <Image
                        src="/images/icons/box.svg"
                        alt="Box Icon"
                        width={24}
                        height={24}
                        className="order-icons img-fluid"
                      />
                      <h6 className="font-13 font-400 mb-0">
                        <span>
                          {orderDetail?.draft_order_package_list?.length ||
                            numberOfPackages}{" "}
                          Pkgs
                        </span>
                      </h6>
                    </div>
                    <div className="d-float-center weight">
                      <Image
                        src="/images/icons/weight.svg"
                        alt="Weight Icon"
                        width={24}
                        height={24}
                        className="order-icons img-fluid"
                      />
                      <h6 className="font-13 font-400 mb-0">
                        <span>{totalWeight} KG</span>
                      </h6>
                    </div>
                  </div>
                  <div className="d-float-center wallet">
                    <Image
                      src="/images/icons/wallet.svg"
                      alt="Wallet Icon"
                      width={24}
                      height={24}
                      className="order-icons img-fluid"
                    />
                    <h6 className="font-13 font-700 mb-0">
                      <span className="color-red-dark">
                        {amountFormatWithCurrency(
                          calculatedTotalShippingCharge || 0
                        )}
                      </span>
                    </h6>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      {customizeOrderModal && (
        <BottomSheetModal
          show={customizeOrderModal}
          onHide={toggle}
          header={false}
        >
          <CustomizeOrderModal
            orderDetails={orderDetail}
            handleChange={handleChange}
          />
        </BottomSheetModal>
      )}
    </>
  );
};

export default OrderCard;
