/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";
// import { usePopup } from "@/context/PopupContext";
import Image from "next/image";
import Link from "next/link";
import { downloadBulkStickerPrint } from "../../../Api/OrderApi";
import { useState } from "react";
import { toast } from "react-toastify";
import Modal from "../../Modal/Modal";
import StickerOrderFilter from "../../Modal/Filters/StickerOrderFilter";
import ScaleLoaderComponent from "../../Loader/ScaleLoader";

export default function Header({}) {
  // const { openPopup } = usePopup();
  const [filterModal, setFilterModal] = useState(false);
  const [filters, setFilters] = useState<any>({});
  const [isDownloading, setIsDownloading] = useState(false);
  const toggleFilter = () => setFilterModal(!filterModal);
  const onSaveFilter = (appliedFilters: any) => {
  //   {
  //     "serviceTypes": {
  //         "id": 1,
  //         "name": "Express"
  //     },
  //     "orderFlowType": {
  //         "id": 1,
  //         "name": "Forward"
  //     },
  //     "orderId": "02152410000315",
  //     "customerOrderId": "333333",
  //     "deliveryMobile": "+97333333333",
  //     "countryCode": "+973",
  //     "orderStatus": [
  //         2,
  //         3
  //     ],
  //     "packageId": "STD24600110",
  //     "noOfPackages": "10",
  //     "packageWeight": "1",
  //     "packageValue": "21",
  //     "packageStatus": null,
  //     "blockNumber": null,
  //     "roadNumber": null,
  //     "buildingNumber": null,
  //     "flatNumber": "",
  //     "printSize": "80*55"
  // }
    setFilters(appliedFilters);
    setFilterModal(false);
    handleDownloadStickers(appliedFilters); // download after applying filters
  };
  
  const handleDownloadStickers = async (appliedFilters: any = {}) => {
    try {
      setIsDownloading(true);
      const payloadFilter = {
        filter_by_service_type: appliedFilters?.serviceTypes?.id,
        filter_by_order_flow_type: appliedFilters?.orderFlowType?.id,
        filter_by_generated_order_id: appliedFilters?.orderId,
        fitler_by_customer_input_order_id: appliedFilters?.customerOrderId,
        filter_by_destination_mobile_number: appliedFilters?.deliveryMobile,
        filter_by_status: appliedFilters?.orderStatus,
        filter_by_generated_order_package_id: appliedFilters?.packageId,
        filter_by_total_no_of_packages: appliedFilters?.noOfPackages,
        filter_by_weight: appliedFilters?.packageWeight,
        filter_by_customer_input_package_value: appliedFilters?.packageValue,
        filter_by_package_status: appliedFilters?.packageStatus,
        size: appliedFilters?.printSize,
      }
      const filteredPayload = Object.entries(payloadFilter).reduce((acc, [key, value]) => {
        if (
          value !== undefined &&
          value !== null &&
          value !== "" &&
          !(Array.isArray(value) && value.length === 0) &&
          value !== 0
        ) {
          acc[key] = value;
        }
        return acc;
      }, {} as Record<string, any>);
      // Call API with filters
      const response = await downloadBulkStickerPrint(appliedFilters?.printSize || "6*4", filteredPayload);
      // ✅ Check for failure
      if (response === null) {
        toast.error(
          response?.message ||
           "No packages found for sticker generation" || "Failed to download stickers. Please try again."
        );
        return; // ⛔ Stop here, don’t try to download
      }
      const blob = new Blob([response], { type: "application/pdf" });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", `bulk-stickers.pdf`);
      document.body.appendChild(link);
      link.click();
      link.parentNode?.removeChild(link);
      setFilters({})
      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 {
      setFilters({})
      setIsDownloading(false);
    }
  };

  return (
    <>
    {isDownloading && <ScaleLoaderComponent />}
    <style>
      {
        `
          .header-right-sticker {
            width: 180px !important;
            color: #fff !important;
          }
          .header-right-sticker .badge-print {
              border: 1px solid #fff !important;
              margin-left: auto !important;
              margin-right: 20px;
              display: block;
              width: max-content !important;
              padding: 8px 15px !important;
              padding-left: 15px !important;
          }
          .badge-print:hover {
            border: 1px solid #010a8b !important;
            background-color: #fff;
            color: #010a8b !important;
          }
        `
      }
    </style>
      {" "}
      <div className="header header-fixed header-logo-left bg-purple shadow-l">
        <Link href="/dashboard" className="header-title color-white">
          <Image 
          className="company-header-logo"
            src="/images/app/logo_white.png"
            alt="Company Logo"
            width={90}
            height={36} // or adjust height to maintain aspect ratio
            priority // optional: improves LCP by preloading the image
          />{" "}
        </Link>

        {/* <Link href="/address-print" className="header-icon header-icon-1 header-right-sticker" title="Print all sticker"> */}
        <Link
  href="#"
  className="header-icon header-icon-1 header-right-sticker"
  title="Print all sticker"
  onClick={(e) => {
    e.preventDefault();
    toggleFilter(); // open filter modal instead of downloading directly
  }}
>
  <span className="badge badge-domestic rounded-xl font-12 position-relative badge-print">
    <i className="fa fa-file-pdf" aria-hidden="true" />{" "}
    &nbsp;&nbsp;
    <span>{isDownloading ? "Downloading..." : "Print all sticker"}</span>
  </span>
</Link>


        {/* <Link href="/notification" className="header-icon header-icon-1"> */}
          {/* <i className="fas color-white fa-bell"></i>
          <span className="badge bg-green-dark">5</span> */}
        {/* </Link> */}
        {/* <a
          href="#"
          //   onClick={() => handleModal("language")}
          onClick={openPopup}
          data-menu="menu-language"
          className="header-icon header-icon-2"
        > */}
          {/* <i className="fas color-white fa-globe color-red-light"></i> */}
        {/* </a> */}
        {/* <a href="#" data-toggle-theme className="header-icon header-icon-3 show-on-theme-dark"><i className="fas fa-sun"></i></a> */}
        {/* <a href="#" data-toggle-theme className="header-icon header-icon-3 show-on-theme-light"><i className="fas fa-moon"></i></a> */}
        {/* <div className="ms-auto me-4 pe-2 header-icon header-icon-3">
            <div className="custom-control ios-switch ios-switch-icon">
                <input type="checkbox" className="ios-input" id="toggle-id-3" />
                <label className="custom-control-label" htmlFor="toggle-id-3"></label>
                <span>AR</span>
                <span>EN</span>
            </div>
        </div> */}
      </div>
      {filterModal && (
  <Modal
    show={filterModal}
    onHide={toggleFilter}
    header={false}
    title=""
    fullscreen={"xl"}
    centered={true}
    classname="custom-center-modal"
    position={"top"}
  >
    <StickerOrderFilter 
      onHide={toggleFilter} 
      onSaveFilter={onSaveFilter} 
      filters={filters} 
    />
  </Modal>
)}

    </>
  );
}
