/* eslint-disable @next/next/no-img-element */
/* eslint-disable jsx-a11y/role-supports-aria-props */
/* eslint-disable @typescript-eslint/no-explicit-any */
import Link from "next/link";
import React from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
  amountFormatWithCurrency,
  cryptoHandler,
  formatDate,
  getFormattedAddress,
  getOrderStatusInfo,
} from "../../../lib/Helper";
import { getBulkOrderDetails } from "../../../Api/OrderApi";
import HourGlassLoader from "../../Loader/Loader";
interface OrderPackage {
  id: string;
  qrCode: string;
  generatedOrderPackageId: string;
  weight: number;
  packageDescription: string;
  customerInputPackageValue: string;
  status: {
    id: number;
    name: string;
  };
}

interface OrderData {
  id: string;
  generatedOrderId: string;
  destinationCustomerName: string;
  destinationMobileNumber: string;
  destinationAlternateNumber: string;
  destination_block_details?: { name: string };
  destination_road_details?: { name: string };
  destination_building_details?: { name: string };
  destinationFlatOrOfficeNumber: string;
  orderType: { name: string };
  status: { id: number };
  barCode: string;
  calculatedTotalShippingCharge: number;
  order_package_list: OrderPackage[];
  totalWeight: number;
  pickupDate: string;
  deliveryInstructions: string;
  codAmount: number;
}

const OrderViewIndex = () => {
  // const router = useRouter();
  const searchParams = useSearchParams();
  const router = useRouter()
  const [orderData, setOrderData] = React.useState<any>({});
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const [packageShow, setPackageShow] = React.useState<boolean>(true);
  // const [isDownloading, setIsDownloading] = React.useState(false);
  const togglePackageShow = () => setPackageShow(!packageShow);

  React.useEffect(() => {
    const fetchOrderDetails = async () => {
      try {
        const encryptedId = searchParams?.get("id");
        if (!encryptedId) {
          setError("No order ID found in URL");
          setIsLoading(false);
          return;
        }

        const decryptedId = cryptoHandler(encryptedId, "decrypt");
        if (!decryptedId) {
          setError("Invalid order ID");
          setIsLoading(false);
          return;
        }

        const orderDetails = await getBulkOrderDetails(decryptedId);
        if (orderDetails && typeof orderDetails === "object") {
          setOrderData(orderDetails as unknown as OrderData);
        } else {
          setError("Invalid order data received");
        }
      } catch (error) {
        console.error("Error fetching order details:", error);
        setError("Failed to load order details. Please try again.");
      } finally {
        setIsLoading(false);
      }
    };

    fetchOrderDetails();
  }, [searchParams]);

  const storedUser = localStorage.getItem("ALL_DATA");
  const allData = storedUser ? JSON.parse(storedUser)?.data : null;

  // const handleDeletePackage = async (packageId: string) => {
  //   if (!packageId) {
  //     toast.error("Invalid package ID");
  //     return;
  //   }

  //   Swal.fire({
  //     title: "Are you sure?",
  //     text: "Do you really want to delete this package?",
  //     icon: "warning",
  //     showCancelButton: true,
  //     confirmButtonText: "Yes, delete it!",
  //     cancelButtonText: "Cancel",
  //     reverseButtons: true,
  //     customClass: {
  //       confirmButton: "delybell-primary px-4",
  //       cancelButton: "delybell-dark",
  //     },
  //   }).then(async (response) => {
  //     if (response?.isConfirmed) {
  //       try {
  //         await deletePackage(packageId);
  //         toast.success("Package deleted successfully");
  //         if (orderData?.id) {
  //           const updatedOrder = await getOrderHistroy(orderData.id);
  //           if (updatedOrder && typeof updatedOrder === "object") {
  //             setOrderData(updatedOrder as unknown as OrderData);
  //           }
  //         }
  //       } catch (error: any) {
  //         console.error("Error deleting package:", error);
  //         toast.error(
  //           error?.response?.data?.message ||
  //             "Failed to delete package. Please try again."
  //         );
  //       }
  //     }
  //   });
  // };

  // const handleDownloadPdf = async () => {
  //   try {
  //     if (!orderData?.invoice_details?.id) {
  //       toast.error("Order ID is not available.");
  //       return;
  //     }
  //     setIsDownloading(true);
  //     const response = await downloadInvoice(orderData?.invoice_details?.id);
  //     const url = window.URL.createObjectURL(new Blob([response]));
  //     const link = document.createElement("a");
  //     link.href = url;
  //     link.setAttribute(
  //       "download",
  //       `invoice-${orderData.generatedOrderId}.pdf`
  //     );
  //     document.body.appendChild(link);
  //     link.click();
  //     link.parentNode?.removeChild(link);
  //     toast.success("Invoice downloaded successfully");
  //   } catch (error: any) {
  //     console.error("Error downloading invoice:", error);
  //     toast.error(
  //       error?.response?.data?.message ||
  //         "Failed to download invoice. Please try again."
  //     );
  //   } finally {
  //     setIsDownloading(false);
  //   }
  // };

  if (isLoading) {
    return <HourGlassLoader />;
  }

  if (error) {
    return (
      <div className="page-content homePageWrap mt-5">
        <div className="card card-style">
          <div className="content">
            <div className="alert alert-danger" role="alert">
              {error}
            </div>
            <Link
              href="/bulk-orders?_=in_progress"
              className="btn btn-full btn-l rounded-s font-600 delybell-primary"
            >
              Back to Orders
            </Link>
          </div>
        </div>
      </div>
    );
  }

  if (!orderData) {
    return (
      <div className="page-content homePageWrap mt-5">
        <div className="card card-style">
          <div className="content">
            <div className="alert alert-warning" role="alert">
              No order data found
            </div>
            <Link
              href="/bulk-orders?_=in_progress"
              className="btn btn-full btn-l rounded-s font-600 delybell-primary"
            >
              Back to Orders
            </Link>
          </div>
        </div>
      </div>
    );
  }

  const handleEdit = (orderDetail: any) => {
    const url = `/create-order?mode=edit_order&orderId=${
      orderDetail?.id
    }&customerName=${encodeURIComponent(
      orderDetail?.destinationCustomerName || ""
    )}`;
    window.location.href = url;
  };
  // const handleEditPackages = (packageId: any, orderDetail: any) => {
  //   const url = `/create-order?mode=edit_order&orderId=${
  //     orderDetail?.id
  //   }&customerName=${encodeURIComponent(
  //     orderDetail?.destinationCustomerName || ""
  //   )}`;
  //   window.location.href = url;
  // };

  return (
    <>
      <style>
        {`
          .order-view-card-top .card-style {
              margin-bottom: 0 !important;
              width: -webkit-fill-available;
              border-bottom: 0 !important;
              border-bottom-left-radius: 0;
              border-bottom-right-radius: 0;
          }
          .order-view-card-bottom .card-style {
              margin-top: 0 !important;
              width: -webkit-fill-available;
              border-top: 0 !important;
              border-top-left-radius: 0;
              border-top-right-radius: 0;
          }
          // .az-content-body-left{
          //     background-image: url(/images/bg/bg-center3.jpg);
          //     background-repeat: no-repeat;
          //     background-position: center;
          //     background-size: cover;
          //     position: relative;
          // }
          @media only screen and (min-device-width : 990px) and (max-device-width : 2000px) {
            .page-content.homePageWrap {
              padding-bottom: 0px;
            }
          }
            .order-view-card-bottom .table > :not(caption) > * > * {
              width: max-content;
            }
        `}
      </style>
      <div
        className="header header-fixed header-logo-app innerHeader header-active bg-white"
        style={{ marginTop: 50 }}
      >
        <Link href="/bulk-orders?_=in_progress" className="header-title">
          {orderData?.generatedOrderId}
        </Link>
        <Link
          href="/bulk-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>
              <Link
                className="dropdown-item"
                href={`#`}
                onClick={() => {
                  // setCustomizeOrderModal(true);
                  handleEdit(orderData);
                }}
              >
                <i className="fa fa-edit me-1" /> Edit Order
              </Link>
            </li>
            <li>
              <Link className="dropdown-item" href="/order-tracking">
                <i className="fa fa-map me-1" /> Track now
              </Link>
            </li>
            <li>
              <a className="dropdown-item" href="#">
                <i className="fa fa-times me-1" /> Cancel Order
              </a>
            </li>
          </ul>
        </div>
      </div>
      <div className="page-content homePageWrap mt-5">
        <div className="row mb-0">
          <div className="col-lg-6 mx-auto">
            <div className="row main-row-box mb-0">
              <div className=" col-lg-12 order-view-card-top">
                <div className="card card-style card-light-border mt-4 mb-0">
                  <div className="content mb-0">
                    <div className="card-info d-float-center justify-content-between mb-3">
                      <div className="">
                        <div className="d-float-center mt-2">
                          <h6 className="font-400 font-16 mb-0 d-float-center fw-bold">
                            {allData?.companyName} {orderData?.generatedOrderId}
                          </h6>
                          <span
                            className={`badge ${
                              getOrderStatusInfo(
                                orderData?.status?.id,
                                orderData
                              )?.color
                            } rounded-xl font-12 px-2 ms-1`}
                          >
                            {
                              getOrderStatusInfo(
                                orderData?.status?.id,
                                orderData
                              )?.text
                            }
                          </span>
                        </div>
                      </div>
                    </div>
                    <div className="order-info-icons d-float-center justify-content-between mt-1 mb-1">
                      <div className="w-100">
                        <div className="d-float-center box">
                          <i className="ri ri-phone-line" aria-hidden="true" />
                          <h6 className="font-13 font-400 mb-0">
                            <span>
                              {orderData?.pickupMobileNumber &&
                              orderData?.pickupAlternateNumber
                                ? `${
                                    orderData?.pickupMobileNumber || " - N/A -"
                                  }, `
                                : `${
                                    orderData?.pickupMobileNumber || "N/A"
                                  } ` || "N/A"}
                              {orderData?.pickupAlternateNumber || "N/A"}
                            </span>
                          </h6>
                        </div>
                        <div className="d-float-center box mt-2 flex-nowrap">
                          <i
                            className="ri ri-map-pin-line"
                            aria-hidden="true"
                          />
                          <h6 className="font-13 font-400 mb-0">
                            <span>
                              {allData?.addressFormatType?.name === "Standard" ? getFormattedAddress() : ""}
                            </span>
                          </h6>
                        </div>
                        <div className="d-float-center justify-content-end mt-3">
                          {/* <p className="mb-2">
                            <span className="badge card-status rounded-xl font-12 px-2">
                              {orderData?.orderType?.name || ""}
                            </span>
                          </p> */}
                          {/* <h6 className="font-13 font-400 mb-0">
                            <Link
                              className="ms-1"
                              href={`/order-tracking?id=${cryptoHandler(
                                orderData?.id,
                                "encrypt"
                              )}`}
                            >
                              <i className="fa fa-map" aria-hidden="true" />
                              &nbsp; <u>Track now</u>
                            </Link>

                            <Link
                              className="ms-3"
                              href={`/address-print?id=${cryptoHandler(
                                orderData?.id,
                                "encrypt"
                              )}`}
                              target="_blank"
                            >
                              <i
                                className="fa fa-file-pdf"
                                aria-hidden="true"
                              />
                              &nbsp; <u>Print Sticker</u>
                            </Link>
                          </h6> */}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="col-lg-12 order-view-card-bottom">
                <div className="card card-style card-light-border mt-4">
                  <div className="content mt-0">
                    <div className="row mb-0 mt-1">
                      <hr className="col-12 my-2 d-lg-none" />
                      <h5 className="col-5 pe-0 text-start font-14 font-400">
                        Pickup date
                      </h5>
                      <h5 className="col-7 text-end font-14 opacity-100">
                        {formatDate(
                          orderData?.pickupDate || ""
                        ) || "---"}
                      </h5>
                      <hr className="col-12 my-2" />
                      <h5 className="col-4 pe-0 text-start font-14 font-400">
                        No.of Orders
                      </h5>
                      <h5 className="col-8 text-end font-14 opacity-100">
                        {orderData?.bulk_order_list?.length || 0}
                      </h5>
                      <hr className="col-12 my-2" />
                      <h5
                        className="col-12 text-start font-14 font-400 d-float-center justify-content-between accordion-btn"
                        data-bs-toggle="collapse"
                        data-bs-target="#collapse2"
                        aria-expanded="false"
                        onClick={togglePackageShow}
                      >
                        Order List
                        <i className="fa fa-chevron-down font-10 accordion-icon" />
                      </h5>
                      {packageShow && (
                        <div
                          id="collapse2"
                          className="col-12"
                          data-bs-parent="#accordion-1"
                        >
                          <div className="table-responsive">
                            <table className="table w-100 border mb-2">
                              <thead>
                                <tr>
                                  <th>Order ID</th>
                                  <td>Weight</td>
                                  <td>Shipping Charge</td>
                                  <td>Status</td>
                                  <td>Action</td>
                                </tr>
                              </thead>
                              <tbody>
                                {orderData?.bulk_order_list?.length > 0 ? (
                                  orderData.bulk_order_list.map(
                                    (item: any, index: number) => (
                                      <React.Fragment key={index}>
                                        <tr>
                                          <th>
                                            <div className="order-qr-id">
                                              {/* <img
                                                src={item?.qrCode}
                                                className="d-block"
                                                alt=""
                                                height={44}
                                                style={{ marginTop: "-5px" }}
                                              /> */}
                                              <a>
                                                {item?.order_details?.generatedOrderId}
                                              </a>
                                            </div>
                                          </th>
                                          <td>{item?.order_details?.totalWeight || 0} Kg</td>
                                          <td>
                                            BHD {item?.order_details?.calculatedTotalShippingCharge || "---"}
                                          </td>
                                          <td>
                                            <span
                                              className={`badge ${
                                                getOrderStatusInfo(
                                                  item?.status?.id,
                                                  item
                                                )?.color
                                              } rounded-xl font-12 px-2`}
                                            >
                                              {item?.order_details?.status?.name || "---"}
                                            </span>
                                          </td>
                                          <button
                                            onClick={() =>
                                              router.push(`/order-view?id=${item?.order_details?.id}`)
                                            }
                                            title="View"
                                          >
                                            {/* <i className="fa fa-print"></i>{" "} */}
                                            View
                                          </button>
                                          {/* {orderData?.status?.id ===
                                          OrderStatus?.Open ? (
                                            <td>
                                              {total?.length > 1 ? (
                                                <>
                                                  <button
                                                    onClick={() =>
                                                      handleEditPackages(
                                                        item?.id,
                                                        orderData
                                                      )
                                                    }
                                                    title="Edit Package"
                                                  >
                                                    <i className="fa fa-edit"></i>
                                                  </button>
                                                  <button
                                                    onClick={() =>
                                                      handleDeletePackage(
                                                        item?.id
                                                      )
                                                    }
                                                    title="Delete Package"
                                                    className="mx-2"
                                                  >
                                                    <i className="fa fa-trash"></i>
                                                  </button>
                                                </>
                                              ) : (
                                                <button
                                                  onClick={() =>
                                                    handleEditPackages(
                                                      item?.id,
                                                      orderData
                                                    )
                                                  }
                                                  title="Edit Package"
                                                >
                                                  <i className="fa fa-edit"></i>
                                                </button>
                                              )}
                                            </td>
                                          ) : (
                                            ""
                                          )} */}
                                        </tr>
                                      </React.Fragment>
                                    )
                                  )
                                ) : (
                                  <tr>
                                    <td colSpan={6}>No Packages Found</td>
                                  </tr>
                                )}
                              </tbody>
                            </table>
                          </div>
                        </div>
                      )}
                      <hr className="col-12 my-2" />
                      <h5 className="col-4 pe-0 text-start font-14 font-400">
                        Total Weight
                      </h5>
                      <h5 className="col-8 text-end font-14 opacity-100">
                        {orderData?.totalWeight || 0} KG
                      </h5>
                      <hr className="col-12 my-2" />
                      <h5 className="col-4 pe-0 text-start font-14 font-400">
                        Pickup Date
                      </h5>
                      <h5 className="col-8 text-end font-14 opacity-100">
                        {orderData?.pickupDate
                          ? `${formatDate(orderData.pickupDate)}`
                          : "---"}
                      </h5>
                      <hr className="col-12 my-2" />
                      <h5 className="col-12 pe-0 text-start font-14 font-400">
                        Pickup Address
                      </h5>
                      <h5 className="col-12 text-start font-14 opacity-100">
                        {getFormattedAddress() || "---"}
                      </h5>
                      <hr className="col-12 my-2" />
                      <h5 className="col-12 pe-0 text-start font-14 font-400">
                        Messages
                      </h5>
                      <h5 className="col-12 text-start font-14 opacity-100">
                        {orderData?.errorMessage || "---"}
                      </h5>
                    </div>
                    <div className="divider" />
                    {/* {allData?.userType?.id ===
                    UserTypes.CorporateCodCustomer ? (
                      <div className="d-flex mb-3">
                        <div>
                          <h5 className="opacity-50 font-500">COD Amount</h5>
                        </div>
                        <div className="ms-auto">
                          <h5 className="text-success">
                            {amountFormatWithCurrency(
                              orderData?.totalCodAmount || ""
                            ) || "---"}
                          </h5>
                        </div>
                      </div>
                    ) : (
                      ""
                    )} */}

                    <div className="d-flex mb-3">
                      <div>
                        <h3 className="font-500">Total Cod Amount</h3>
                      </div>
                      <div className="ms-auto">
                        <h3 className="text-danger">
                          {orderData?.totalCodAmount
                            ? amountFormatWithCurrency(
                                orderData.totalCodAmount || ""
                              )
                            : "---"}
                        </h3>
                      </div>
                    </div>
                    <div className="divider mb-0" />
                  </div>
                  {/* <a
                    href="#"
                    onClick={(e) => {
                      e.preventDefault();
                      if (!isDownloading) handleDownloadPdf();
                    }}
                    className="btn btn-full btn-l rounded-s font-600 delybell-primary mx-3 mb-4"
                    style={
                      isDownloading
                        ? { opacity: 0.6, pointerEvents: "none" }
                        : {}
                    }
                  >
                    {isDownloading ? (
                      <>
                        <i
                          className="fa fa-spinner fa-spin"
                          aria-hidden="true"
                        />{" "}
                        Downloading...
                      </>
                    ) : (
                      <>
                        <i className="fa fa-download" aria-hidden="true" />
                        &nbsp; Download Invoice in PDF
                      </>
                    )}
                  </a> */}
                </div>
              </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={"/images/bg/delivery-man.jpg"}
                alt={""}
              />
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default OrderViewIndex;
