/* eslint-disable @typescript-eslint/no-explicit-any */
import React from "react";
import { downloadBulkStickerPrint, getPackages } from "../../../Api/OrderApi";
import HourGlassLoader from "../../Loader/Loader";
import AddressPrintTemplate from "./Containers/AddressPrintTemplate";
import { useSearchParams } from "next/navigation";
import { OrderFlowType, UserTypes } from "@/Constant/enums";
import { getFormattedAddress } from "../../../lib/Helper";
import AddressPrintTemplateSmall from "./Containers/AddressPrintTemplateSmall";
import AddressPrintTemplateA4 from "./Containers/AddressPrintTemplateA4";
import { toast } from "react-toastify";

interface AddressLabelProps {
  order?: any;
  orderId?: string;
  printSize?: string;
}

const AddressLabel: React.FC<AddressLabelProps> = ({ order: propOrder, orderId, printSize = "" }) => {
  const [orders, setOrders] = React.useState<any[]>(propOrder ? [propOrder] : []);
  const searchParams: any = useSearchParams();
  const pkgId  = searchParams.get("pkg");
  const latestOrderLength = searchParams.get("len") || "";
  const hasQueryParams = typeof window !== "undefined" && window.location.search.length > 0;
  const storedUser = localStorage.getItem("ALL_DATA");
  const allData = storedUser ? JSON.parse(storedUser)?.data : null;

  const getFormattedAddressLines = (value?: any) => {
    return getFormattedAddress(value);
  };
  React.useEffect(() => {
    const fetchOrderData = async () => {
      if ((orderId || pkgId) && !propOrder) {
        try {
          const response = await getPackages({ list_all: true });

          let filtered = response;

          if (pkgId) {
            filtered = response.filter(
              (pkg: any) => pkg?.id === parseInt(pkgId)
            );
          } else if (orderId) {
            filtered = response.filter(
              (pkg: any) => pkg?.order?.id === parseInt(orderId)
            );
          }

          setOrders(filtered || []);
        } catch (error) {
          console.error("Error fetching packages:", error);
        }
      }
    };

    fetchOrderData();
  }, [orderId, pkgId, propOrder]);

  if (!orders || orders.length === 0) {
    return <HourGlassLoader />;
  }

  return (
    <>
      <style>
        {`
          * {
            font-family: "Roboto", sans-serif;
            font-optical-sizing: auto;
            font-style: normal;
            font-weight: 400;
            font-size: 12px;
          }
          ${!latestOrderLength && hasQueryParams ? `
            .print-page:nth-child(1) {
              display: none;
            }
          ` : ""}
        `}
      </style>

      {orders.map((order, index) => {
        const formattedAddressLines = 
        (allData?.addressFormatType?.name === "Standard")
          ? getFormattedAddressLines({
              flatDetails: order?.order?.pickup_flat_or_office_number ?? order?.order?.pickupFlatOrOfficeNumber ?? "",
              buildingDetails: order?.order?.pickup_building_details,
              blockDetails: order?.order?.pickup_block_details,
              roadDetails: order?.order?.pickup_road_details,
            })
          : order?.order?.sender_address || getFormattedAddressLines({
            flatDetails: order?.order?.pickup_flat_or_office_number ?? order?.order?.pickupFlatOrOfficeNumber ?? "",
            buildingDetails: order?.order?.pickup_building_details,
            blockDetails: order?.order?.pickup_block_details,
            roadDetails: order?.order?.pickup_road_details,
          });;
        const recipientAddress =
          allData?.addressFormatType?.name === "Standard"
            ? getFormattedAddressLines({
              flatDetails: order?.order?.destination_flat_or_office_number ?? order?.order?.destinationFlatOrOfficeNumber ?? "",
                buildingDetails: order?.order?.destination_building_details,
                blockDetails: order?.order?.destination_block_details,
                roadDetails: order?.order?.destination_road_details,
              })
            : order?.order?.destination_address || getFormattedAddressLines({
              flatDetails: order?.order?.destination_flat_or_office_number ?? order?.order?.destinationFlatOrOfficeNumber ?? "",
              buildingDetails: order?.order?.destination_building_details,
              blockDetails: order?.order?.destination_block_details,
              roadDetails: order?.order?.destination_road_details,
            });
        const recipientPhoneNumber = [
          order?.order?.destination_mobile_number,
          order?.order?.destination_alternate_number,
        ].filter(Boolean).join(" / ");

        const senderPhoneNumber = [
          order?.order?.pickup_mobile_number,
          order?.order?.pickup_alternate_number,
        ].filter(Boolean).join(" / ");

        const templateOrder = {
          ...order,
          shipByDate: order?.shipByDate,
          weight: order?.totalWeight?.toString(),
          orderId: order?.customerInputOrderId,
          parcelInfo: order?.order?.service_type?.name || "---",
          paymentType:
            order?.order?.created_by_details?.userType?.id === UserTypes?.NormalCustomer
              ? "Prepaid"
              : order?.order?.cod_amount > 0
              ? "COD"
              : "INV",
          recipientName: order?.order?.order_flow_type ===  OrderFlowType.Return ?  order?.order?.created_by_details?.companyName ||
          `${order?.order?.created_by_details?.firstName} ${order?.order?.created_by_details?.lastName}` ||
          "---": order?.order?.destination_customer_name || "---",
          senderName: order?.order?.order_flow_type ===  OrderFlowType.Return ? order?.order?.destination_customer_name || "---" :
            order?.order?.created_by_details?.companyName ||
            `${order?.order?.created_by_details?.firstName} ${order?.order?.created_by_details?.lastName}` ||
            "---",
          recipientAddress: recipientAddress,
          senderAddress: formattedAddressLines,
          recipientPhone: order?.destinationCustomerPhone,
          boxInfo: order?.generated_order_package_id || "---",
          blockNo:
            order?.order?.destination_block_details?.code ||
            order?.order?.destination_block_details?.name ||
            "---",
          packageDescription: order?.package_description || "---",
          senderPostcode: order?.senderPostcode,
          amount: order?.amount?.toString(),
          deliveryType: order?.order?.service_type?.name || "",
          trackingNumber: order?.trackingNumber,
          recipientPhoneNumber: recipientPhoneNumber || "", 
          senderPhoneNumber: senderPhoneNumber || "",
          isReturnOrder: order?.order?.order_flow_type ===  OrderFlowType.Return ? true : false
        };
        return (
          <div key={index}>
            {printSize === "80x55" ? (
              <AddressPrintTemplateSmall order={templateOrder} />
            ) : printSize === "A4" ? (
              <AddressPrintTemplateA4 order={templateOrder} />
            ) : (
              <AddressPrintTemplate order={templateOrder} />
            )}
            {orders.length > 1 && <hr style={{ margin: "20px 0" }} />}
          </div>
        );
      })}
    </>
  );
};

export default function AddressPrint() {
  const [orders, setOrders] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [printSize, setPrintSize] = React.useState("6x4"); // Default size
  const addressRef = React.useRef<HTMLDivElement>(null);
  const searchParams: any = useSearchParams();
  const orderId = searchParams.get("id");
  const latestOrderLength = searchParams.get("len") || "";

  React.useEffect(() => {
    const fetchOrders = async () => {
      setIsLoading(true);
      try {
        const orderList: any = await getPackages({
          list_all: latestOrderLength ? false : true,
          limit: latestOrderLength,
        });
        setOrders(orderList);
      } catch (error) {
        console.error("Failed to fetch orders:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchOrders();
  }, [latestOrderLength]);

  // const handlePrintOld = () => {
  //   if (addressRef.current) {
  //     const printWindow = window.open("", "_blank", "width=400,height=600");

  //     let printStyle = "";
  //     if (printSize === "6x4") {
  //       printStyle = `
  //         <style>
  //           @page { size: 6in 4in; margin: 0; }
  //           body { margin: 0; padding: 0; }
  //           .address-container { width: 6in; height: 4in; }
  //         </style>
  //       `;
  //     } else if (printSize === "80x55") {
  //       printStyle = `
  //         <style>
  //           @page { size: 80mm 55mm; margin: 0; }
  //           body { margin: 0; padding: 0; }
  //           .address-container { width: 80mm; height: 55mm; }
  //         </style>
  //       `;
  //     }

  //     printWindow?.document.write(
  //       `<html><head><title>Print</title>${printStyle}</head><body>`
  //     );
  //     printWindow?.document.write(addressRef.current.innerHTML);
  //     printWindow?.document.write("</body></html>");
  //     printWindow?.document.close();
  //     printWindow?.focus();
  //     printWindow?.print();
  //   }
  // };
  const handlePrint = () => {
    const content = document.getElementById("print-content");
    const printWindow: any = window.open("", "_blank", "width=700,height=700");
    const itemsHTML = Array.from(content?.children || [])
    .filter((child) => child?.innerHTML.trim() !== "")
    .map((child, index, arr) => {
      const isLast = index === arr.length - 1;
      return `
        <div class="print-page${isLast ? " last-page" : ""}${printSize === "A4" ? " a4-size" : ""}">
          ${child.outerHTML}
        </div>
      `;
    }).join("");
  
    printWindow.document.write(`
      <html>
        <head>
          <title>Print</title>
          <style>
            @media print {
              @page {
                ${printSize === "A4" ? "size: A4;" : printSize === "80x55demo" ? "size: 80mm 55mm;" : "size: 4in 7in;"}
                margin: 0;
              }
  
              body, html {
                margin: 0;
                padding: 0;
              }
  
              .print-content {
                width: 100%;
                height: 100%;
                padding: 0.1in;
                margin-bottom: 0.1in;
                // /* Re-enabling flexbox for centering */
                // display: flex;
                // justify-content: center;
                // align-items: center;
              }
  
              .print-page {
                ${printSize === "A4" ? "width: 210mm; height: 297mm;" : printSize === "80x55demo" ? "width: 80mm; height: 55mm;" : "width: 4in; height: 7in;"}
                box-sizing: border-box;
                overflow: hidden;
                page-break-after: always;
                break-after: always;
                page-break-inside: avoid;
                break-inside: avoid;
                padding-top: 0.1in;
              }
  
              .last-page {
                page-break-after: auto !important;
                break-after: auto !important;
              }
            }
          </style>
        </head>
        <body>
            ${itemsHTML}
        </body>
      </html>
    `);
  
    printWindow.document.close();
  
    printWindow.onload = () => {
      const images = printWindow.document.images;
      let loadedCount = 0;
  
      const checkAllImagesLoaded = () => {
        loadedCount++;
        if (loadedCount === images.length) {
          printWindow.focus();
          printWindow.print();
          printWindow.close();
        }
      };
  
      if (images.length === 0) {
        printWindow.focus();
        printWindow.print();
        printWindow.close();
      } else {
        for (const img of images) {
          if (img.complete) {
            checkAllImagesLoaded();
          } else {
            img.onload = checkAllImagesLoaded;
            img.onerror = checkAllImagesLoaded;
          }
        }
      }
    };
  };
  
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [isDownloading, setIsDownloading] = React.useState(false);

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handleDownloadStickers = async () => {
  try {
    setIsDownloading(true);

    // Call API with the selected print size
    const size = printSize.replace("x", "*");
    const response = await downloadBulkStickerPrint(size ?? "");

    // Convert response to Blob
    const blob = new Blob([response], { type: "application/pdf" });
    const url = window.URL.createObjectURL(blob);

    // Create a temporary link to download
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", `bulk-stickers-${printSize}.pdf`);
    document.body.appendChild(link);
    link.click();
    link.parentNode?.removeChild(link);

    toast.success("Stickers downloaded successfully");
  } catch (error: any) {
    console.error("Error downloading stickers:", error);
    toast.error(
      error?.response?.data?.message || "Failed to download stickers. Please try again."
    );
  } finally {
    setIsDownloading(false);
  }
};
  return (
    <>
      <style>{`
      body { padding-top: 0; }
      `}</style>
      <div className="col-12 px-1 py-2">
        <div className="w-100 text-center">
          <div className="mb-2">
            <select
              className="form-select form-select-sm d-inline w-auto me-2"
              value={printSize}
              onChange={(e) => setPrintSize(e.target.value)}
            >
              <option value="6x4">6 x 4 inches</option>
              <option value="80x55">80 x 55 mm</option>
              <option value="A4">A4 (210 x 297 mm)</option>
            </select>
            <button
              className="btn btn-xxs mt-2 mb-3 rounded-s text-uppercase font-700 shadow-s bg-highlight delybell-primary"
              onClick={handlePrint}
            >
              <i className="fa fa-print"></i> Print
            </button>
            {/* <button
  className="btn btn-xxs mt-2 mb-3 rounded-s text-uppercase font-700 shadow-s bg-success ms-2"
  onClick={handleDownloadStickers}
  disabled={isDownloading} // disable button while downloading
>
  <i className="fa fa-file-pdf"></i>{" "}
  {isDownloading ? "Downloading..." : "Download All Stickers"}
</button> */}


          </div>
        </div>

        <div className="address-container" ref={addressRef} id="print-content">
          {isLoading ? (
            <HourGlassLoader />
          ) : orderId ? (
            <AddressLabel orderId={orderId} printSize={printSize} />
          ) : (
            orders.map((order, index) => (
              <div key={index} className="order-item" >
                <AddressLabel order={order} printSize={printSize}/>
              </div>
            ))
          )}
        </div>
      </div>
    </>
  );
}
