/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @next/next/no-img-element */
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import {
  cryptoHandler,
  formatDate,
  formatTime,
  getFormattedAddress,
  getOrderStatusInfo,
  truncateWithTooltip,
} from "../../../lib/Helper";
import React, { useState } from "react";
import { getOrderHistroy } from "../../../Api/OrderApi";
import HourGlassLoader from "../../Loader/Loader";
import { OrderFlowType } from "@/Constant/enums";

export default function OrderTracking() {
  const storedUser = localStorage.getItem("ALL_DATA");
  const allData = storedUser ? JSON.parse(storedUser)?.data : null;
  const searchParams: any = useSearchParams();
  const [orderData, setOrderData] = React.useState<any>({});
  const [isLoading, setIsLoading] = React.useState(true);
  const [orderId, setOrderId] = useState<any>(null);

  React.useEffect(() => {
    const fetchOrderDetails = async () => {
      try {
        const encryptedId: any = searchParams.get("id") || "";
        if (!encryptedId) {
          console.error("No id found in URL");
          setIsLoading(false);
          return;
        }
        const decryptedId = cryptoHandler(encryptedId, "decrypt");
        if (!decryptedId) {
          console.error("Decryption failed");
          setIsLoading(false);
          return;
        }
        const orderDetails = await getOrderHistroy(decryptedId);
        setOrderId(decryptedId);
        setOrderData(orderDetails);
      } catch (error) {
        console.error("Error fetching order details:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchOrderDetails();
  }, [searchParams]);

  const timelineStages = [
    {
      name: "Order Placed",
      statusIds: [1], // OrderPlaced
      description: "Order has been placed successfully",
    },
    {
      name: "Order Picked",
      statusIds: [2], // OrderPicked
      description: "Order has been picked up from customer",
    },
    {
      name: "At Warehouse",
      statusIds: [3], // AtWarehouse
      description: "Order is at warehouse",
    },
    {
      name: "In Transit",
      statusIds: [9], // InTransitToWarehouse
      description: "Order is in transit to destination warehouse",
    },
    {
      name: "At Destination Warehouse",
      statusIds: [10], // AtDestinationWarehouse
      description: "Order is at destination warehouse",
    },
    {
      name: "Out For Delivery",
      statusIds: [4], // OutForDeliveryFromWarehouse, OutForDelivery
      description: "Order is out for delivery",
    },
    {
      name: "Exception",
      statusIds: [6], // ExceptionOccurred, Exception
      description: "Exception occurred during delivery",
    },
    {
      name: "Out For Delivery After Exception",
      statusIds: [7], // OutForDeliveryAfterException
      description: "Order is out for delivery after resolving exception",
    },
    {
      name: "Delivered",
      statusIds: [5, 8], // DeliveredAfterException, Delivered
      description: "Order has been delivered successfully",
    },
  ];

  // For non-transit orders (simpler flow)
  const nonTransitTimelineStages = [
    {
      name: "Order Placed",
      statusIds: [1], // OrderPlaced
      description: "Order has been placed successfully",
    },
    {
      name: "Order Picked",
      statusIds: [2], // OrderPicked
      description: "Order has been picked up from customer",
    },
    {
      name: "At Warehouse",
      statusIds: [3], // AtWarehouse
      description: "Order is at warehouse",
    },
    {
      name: "Out For Delivery",
      statusIds: [4], // OutForDelivery
      description: "Order is out for delivery",
    },
    {
      name: "Exception",
      statusIds: [6], // ExceptionOccurred, Exception
      description: "Exception occurred during delivery",
    },
    {
      name: "Delivered",
      statusIds: [5], // Delivered
      description: "Order has been delivered successfully",
    },
  ];

  // Determine if this is a transit order based on order history
  const isTransitOrder =
    orderData?.order_history?.some((h: any) =>
      [15, 16, 17, 18, 19, 20].includes(h.action.id)
    ) || false;

  const currentStatusId = orderData?.status?.id;
  const isCancelled = currentStatusId === 12; // Cancelled status

  // Use appropriate timeline based on order type
  const activeTimelineStages = isTransitOrder
    ? timelineStages
    : nonTransitTimelineStages;
  return (
    <>
      <style>
        {`          
          @media only screen and (min-device-width : 990px) and (max-device-width : 2000px) {
            .page-content.homePageWrap {
              padding-bottom: 0;
            }
          }
        `}
      </style>
      {isLoading && <HourGlassLoader />}
      <div className="order-tracking device-is-android ms-lg-5" id="page">
        <div
          className="header header-fixed header-logo-app innerHeader header-active bg-white"
          style={{ marginTop: 50 }}
        >
          <Link
            href={`/order-view?id=${cryptoHandler(orderId, "encrypt")}`}
            className="header-title"
          >
            Order Tracking
          </Link>
          <Link
            href="/my-orders?_=in_progress"
            className="header-icon header-icon-1"
          >
            <i className="fas fa-chevron-left" />
          </Link>
          <div className="dropdown order-view-dropdown color-theme show-on-theme-light header-icon header-icon-2 font-16">
            <button
              className="dropdown-toggle"
              type="button"
              id="dropdownMenuButton1"
              data-bs-toggle="dropdown"
              aria-expanded="false"
            >
              {/* <i className="fa fa-ellipsis-v" aria-hidden="true" /> */}
            </button>
            <ul className="dropdown-menu" aria-labelledby="dropdownMenuButton1">
              <li>
                <a className="dropdown-item" href="#">
                  <i className="fa fa-phone me-1" /> Contact Support
                </a>
              </li>
              {/* <li><a class="dropdown-item" href="order-tracking.php"><i class="fa fa-map me-1"></i> Track now</a></li> */}
              {/* <li><a class="dropdown-item" href="#"><i class="fa fa-times me-1"></i> Cancel Order</a></li> */}
            </ul>
          </div>
        </div>
        <div className="track-view ms-lg-3">
          <div className="row mb-0">
            <div className="col-lg-6">
              <div className="timeline-cover timeline-cover-center position-relative h-auto">
                <div
                  data-card-height={220}
                  className="card card-style card-light-border"
                  style={{ height: 220, marginTop: 70 }}
                  data-ll-status="loaded"
                >
                  <div className="card-center text-center mb-3">
                    <div className="d-float-center1 justify-content-center mt-0">
                      <img
                        height={60}
                        className="img-qr-code"
                        src={orderData?.barCode}
                        alt={""}
                      />
                      <div className="head-content mx-2">
                        <h1 className="font-16 mt-1 mb-0 pb-0">
                          AWB No: {orderData?.generatedOrderId || "---"}
                        </h1>
                        <div className="d-float-center justify-content-center mb-3 mt-2">
                          <h6 className="font-500 font-16 mb-0 mt-0">
                            <span className="text-dark" title={orderData?.destinationCustomerName || ""}>
                              {truncateWithTooltip(orderData?.destinationCustomerName || '', 50).text || "---"}
                            </span>
                          </h6>
                          <span
                            className={`badge open-status rounded-xl font-12 px-2 ${
                              getOrderStatusInfo(
                                orderData?.status?.id,
                                orderData
                              )?.color
                            }`}
                          >
                            {
                              getOrderStatusInfo(
                                orderData?.status?.id,
                                orderData
                              )?.text
                            }
                          </span>
                          {orderData?.orderFlowType?.id === OrderFlowType.Return ? (
                                <span
                                  className={`badge bg-purple rounded-xl font-12 px-2`}
                                >
                                  {
                                    orderData?.orderFlowType?.name
                                  }
                                </span>
                              ) : ''}
                        </div>
                        <p
                          className="opacity-90 font-11 mb-0 mt-1 mb-2"
                          style={{ lineHeight: "1.5" }}
                        >
                          <i className="ri ri-map-pin-line me-1"></i>
                          <span>
                            {/* getFormattedAddress(orderData, 'order_summary') */}
                            {allData?.addressFormatType?.name === "Standard"
                              ? getFormattedAddress(orderData, "order_summary")
                              : orderData?.destinationAddress || ""}
                          </span>
                        </p>
                      </div>
                    </div>
                    {/* <a className="font-14 font-500" href="#"><i className="ri-phone-line"></i> &nbsp;Call</a> */}
                    {/* <a
                      href={`tel: ${orderData?.destinationMobileNumber}`}
                      className={`py-2 btn-s rounded-xl ${
                        getOrderStatusInfo(orderData?.status?.id, orderData)?.color
                      } font-800 text-uppercase text-white`}
                    >
                      {getOrderStatusInfo(orderData?.status?.id, orderData)?.text}
                    </a> */}
                  </div>
                  {/* <div class="card-overlay bg-black opacity-80"></div> */}
                </div>
              </div>
              <div className="page-content innerPageWrap trackingPageWrap">
                <div className="timeline-body mt-0">
                  <div className="timeline-deco" />

                  {!isCancelled &&
                    activeTimelineStages
                      .filter((stage) => {
                        // If non-transit and stage is "Exception", include only if it's in the order history
                        if (!isTransitOrder && stage.name === "Exception") {
                          return orderData?.order_history?.some((h: any) =>
                            stage.statusIds.includes(h.action.id)
                          );
                        }
                        return true; // Include all others
                      })
                      .map((stage, index) => {
                        const stageHistory =
                          orderData?.order_history?.filter((h: any) =>
                            stage.statusIds.includes(h.action.id)
                          ) || [];
                        const isCompleted = stageHistory.length > 0;
                        const isException = stage.name === "Exception";
                        return (
                          <div key={index} className="timeline-item mt-3">
                            <i
                              className={`timeline-icon shadow-l ${
                                isCompleted
                                  ? isException
                                    ? "bg-red-dark"
                                    : "bg-green-dark"
                                  : "bg-white border"
                              }`}
                            />{" "}
                            <div
                              className={`timeline-item-content ${
                                !isCompleted ? "opacity-40" : ""
                              }`}
                            >
                              <h6 className="font-600 font-15 mb-0">
                                {stage.name}
                              </h6>

                              {isCompleted ? (
                                stageHistory.map(
                                  (history: any, hIndex: number) => (
                                    <div key={hIndex} className="pt-2">
                                      <p className="font-13 font-500 mb-0">
                                        {history.remarks || stage.description}
                                      </p>
                                      <p className="font-11 opacity-60 mb-0">
                                        {formatDate(history.createdAt)} -{" "}
                                        {formatTime(history.createdAt)}
                                      </p>
                                    </div>
                                  )
                                )
                              ) : (
                                <p className="font-13 font-400 mb-0 pt-2">
                                  {stage.description}
                                </p>
                              )}
                            </div>
                          </div>
                        );
                      })}

                  {isCancelled && (
                    <div className="timeline-item mt-2">
                      <i className="bg-red-dark shadow-l timeline-icon" />
                      <div className="timeline-item-content">
                        <h6 className="font-500 font-14 pt-1 pb-1 mb-0">
                          Order Cancelled
                        </h6>
                        {orderData?.order_history?.find(
                          (h: any) => h.action.id === 10
                        ) && (
                          <p className="text-dark font-12">
                            {
                              orderData.order_history.find(
                                (h: any) => h.action.id === 10
                              ).remarks
                            }
                          </p>
                        )}
                      </div>
                    </div>
                  )}
                </div>
                {/* /.timeline-body */}
                <div className="col-md-12 timeline-item-content ps-0 mt-3">
                  <Link
                    href={`/order-view?id=${cryptoHandler(
                      orderData?.id,
                      "encrypt"
                    )}`}
                    className="mb-3 rounded-xl font-600 border-blue-dark color-blue"
                  >
                    View Order Details{" "}
                    <i className="fa fa-angle-right" aria-hidden="true" />
                  </Link>
                </div>
              </div>
            </div>
            <div className="col-lg-6">
              <div className="d-lg-block d-none img-track-box h-100 bg-white">
                <img
                  className="img-track w-100 h-100 object-fit-contain"
                  // src={orderData?.barCode || "/images/bg/delivery-man.jpg"}
                  src={"/images/bg/delivery-man.jpg"}
                  alt={""}
                />
              </div>
            </div>
          </div>
        </div>
        {/* <div data-menu-load="menu-footer.html"></div> */}
      </div>
    </>
  );
}
