/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import { ImagePath } from "@/Constant";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { useSearchParams } from "next/navigation";
import { getSingleSettledView, uploadManifest, manifestColumnMapping } from "../../../../Api/ShipmentApi";

// Assume these components exist or adjust import paths accordingly
import Header from "./ViewContainers/Header";
import TableManifest from "./ViewContainers/TableManifest";
import Footer from "./ViewContainers/Footer";
import Modal from "../../../Modal/Modal";
import ManifestColumnsForm from "./ManifestColumnsForm";
import { ShipmentStatus } from "@/Constant/enums";

const ShipmentPreview = ({ editShipment, setShipmentDetails }: any) => {
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [manifestResponse, setManifestResponse] = useState<any>(null);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const [isMappingModalOpen, setIsMappingModalOpen] = useState(false);
  const [mappingSelections, setMappingSelections] = useState<Record<string, number | "">>({});
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [mappingFilter, setMappingFilter] = useState("");
  const [isSavingMapping, setIsSavingMapping] = useState(false);
  const [PriceList] = useState({
    customer_details: {
      companyName: "Acme Corp",
      address: "123 Main St, Springfield",
      phone: "1234567890",
      email: "info@acmecorp.com",
    },
    settlementId: "SETTLE123456",
    shipment_summary: {
      totalAmount: 5000,
      currency: "USD",
    },
    shipments: [
      {
        shipmentId: "SHIP123",
        containerNumber: "CONT001",
        origin: "New York",
        destination: "Dubai",
        items: [
          {
            name: "Electronics",
            quantity: 10,
            weight: 200,
            price: 1500,
          },
        ],
      },
    ],
  });

  const searchParams = useSearchParams();
  const id = searchParams.get("id");
  const componentRef = useRef<HTMLDivElement | null>(null);

  const handleUploadManifest = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault(); // Prevent form submission
    e.stopPropagation(); // Stop event from bubbling up to modal
    setUploadError(null);

    if (fileInputRef.current) {
      fileInputRef.current.value = "";
      fileInputRef.current.click();
    }
  };


  const handleManifestFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    try {
      const file = e.target.files?.[0];
      if (!file) return;

      const shipmentId = editShipment?.id ?? (id ? Number(id) : undefined);
      if (!shipmentId) {
        setUploadError("Shipment ID is required");
        return;
      }

      setIsUploading(true);
      const result = await uploadManifest({
        manifest_file: file,
        shipment_id: shipmentId,
        metadata: {
          uploaded_at: new Date().toISOString(),
          file_name: file.name,
          file_size: file.size,
        },
      });

      if (result.success) {
        setManifestResponse(result.data);
        const initialSelections: Record<string, number | ""> = {};
        (result as any)?.data?.originalColumns?.forEach((col: any) => {
          initialSelections[col.variable] = "";
        });
        setMappingSelections(initialSelections);
        setIsMappingModalOpen(true);
      } else {
        setUploadError(result.error || "Failed to upload manifest");
        console.error("Manifest upload failed:", result.error, result.data);
      }
    } catch (error: any) {
      setUploadError(error?.message || "An unexpected error occurred during upload");
    } finally {
      setIsUploading(false);
    }
  };

  const handlePrints = () => {
    const content = document.getElementById("print-area");
    const printWindow: any = window.open("", "_blank", "width=700,height=700");

    printWindow.document.write(`
      <html>
        <head>
          <title>Print</title>
          <style>
            @media print {
              @page {
                size: 7in 7in;
                margin: 0;
              }
              body {
                margin: 0;
                padding: 0;
              }
              .print-content {
                padding: 0.02in;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                color-adjust: exact;
              }
            }
          </style>
        </head>
        <body>
          <div class="print-content">
            ${content?.innerHTML || ""}
          </div>
        </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;
          }
        }
      }
    };
  };

  const { isLoading: isPriceListLoading } = useQuery({
    queryKey: ["getSingleSettledView", id],
    queryFn: () => (id ? getSingleSettledView(id) : Promise.resolve(null)),
    enabled: !!id,
  });

  const downloadPDF = () => {
    const input: any = document.getElementById("pdf-content");

    html2canvas(input).then((canvas) => {
      const imgData = canvas.toDataURL("image/png");
      const pdf = new jsPDF();
      const imgWidth = 200;
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      const margin = 10;
      pdf.addImage(
        imgData,
        "PNG",
        margin,
        margin,
        imgWidth - 2 * margin,
        imgHeight - 2 * margin
      );
      const fileName = `Settlement_${PriceList?.customer_details?.companyName || ""
        }_${PriceList?.settlementId || ""}.pdf`;
      pdf.save(fileName);
    });
  };

  return (
    <>
      <style>
        {`
        .px-28 {
            padding: 13px 28px !important;
        }
            thead, tbody, tfoot, tr, td, th {
    border-color: #333;
    border-style: solid;
    border-width: 1px;
}
      `}
      </style>
      {editShipment?.status?.id === ShipmentStatus.Created ? (
        <div className="d-float-center w-100 justify-content-center gap-20 mt-0">
          <input
            ref={fileInputRef}
            type="file"
            accept=".xlsx,.xls,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            onChange={handleManifestFileChange}
            style={{ display: "none" }}
          />
          <button
            onClick={downloadPDF}
            className="btn btn-m rounded-m delybell-primary font-700 text-uppercase flex-fill01 text-center w-auto px-28"
          >
            <i className="fa fa-print me-1" /> Print
          </button>

          {/* <button
        // onClick={handleImportManifest}
        className="btn btn-m rounded-m delybell-blue font-700 text-uppercase flex-fill01 text-center w-auto px-28"
      >
        <i className="fa fa-file-import me-1" /> Import Manifest
      </button> */}

          <button
            onClick={handleUploadManifest}
            disabled={isUploading}
            className="btn btn-m rounded-m bg-purple font-700 text-uppercase flex-fill01 text-center w-auto px-28"
          >
            <i className="fa fa-file-upload me-1" /> {isUploading ? "Uploading..." : "Upload Manifest"}
          </button>
        </div>
      ) : ''}
      {isMappingModalOpen && (
        <Modal
          show={isMappingModalOpen}
          onHide={() => {
            setIsMappingModalOpen(false)
          }}
          header={false}
          title=""
          // fullscreen={"sm"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >               <div
          id="menu-wizard-step-1"
          className="menu menu-box-right bg-white sendPackageBox menu-active"
          data-menu-height="cover"
          data-menu-width="cover"
          onClick={(e) => e.stopPropagation()}>
            <ManifestColumnsForm
              setIsMappingModalOpen={setIsMappingModalOpen}
              uploadError={uploadError}
              manifestResponse={manifestResponse}
              mappingSelections={mappingSelections}
              setMappingSelections={setMappingSelections}
              mappingFilter={mappingFilter}
              isSavingMapping={isSavingMapping}
              setIsSavingMapping={setIsSavingMapping}
              setUploadError={setUploadError}
              manifestColumnMapping={manifestColumnMapping}
              editShipment={editShipment}
              id={id}
              setShipmentDetails={setShipmentDetails}
            />
          </div>
        </Modal>
      )}
      <div className="scrollWrap order-list-step3 mt-0">
        {isPriceListLoading && (
          <div className="mb-3 d-float-center justify-content-between">
            <h5 className="mb-0">{isPriceListLoading ? "Loading..." : ``}</h5>
          </div>
        )}
        <div className="row mx-0">
          <div className="col-md-12 pb-3 invoice-page01">
            <div
              className="col-md-12 pb-3 mx-auto invoice-page01"
              id="pdf-content"
              ref={componentRef}
            >
              <table
                className="w-100 mt-2"
                style={{
                  maxWidth: "auto",
                  margin: "auto",
                  border: "1px solid #eee",
                  display: "block!important",
                }}
                id="print-area"
              >
                <tbody>
                  <tr>
                    <td
                      className="text-center"
                      style={{
                        border: 0,
                        padding: 0,
                        backgroundImage: `url(${ImagePath}/app/Delybell-Shipping-Invoice.jpg)`,
                        backgroundSize: "cover",
                        backgroundRepeat: "no-repeat",
                      }}
                    >
                      <Header PriceList={editShipment} />
                      <TableManifest PriceList={editShipment} />
                      <Footer />
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
      {false && (
        <div className="d-flex justify-content-center gap-2 py-3">
          <button className="btn btn-primary" onClick={handlePrints}>
            Print
          </button>
          <button className="btn btn-secondary" onClick={downloadPDF}>
            Download PDF
          </button>
        </div>
      )}
    </>
  );
};

export default ShipmentPreview;
