import html2canvas from "html2canvas";
import jsPDF from "jspdf";

export const downloadPdf = async (
  elementId: string,
  pdfFileName: string,
  setLoading: (loading: boolean) => void,
) => {
  setLoading(true);
  try {
    const input = document.getElementById(elementId);
    if (input) {
      const canvas = await html2canvas(input);
      const imgData = canvas.toDataURL("image/png");
      const pdf = new jsPDF({
        orientation: "portrait",
        unit: "mm",
        format: "a4",
      });

      const imgProperties = pdf.getImageProperties(imgData);
      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = (imgProperties.height * pdfWidth) / imgProperties.width;

      pdf.addImage(imgData, "PNG", 0, 0, pdfWidth, pdfHeight);
      pdf.save(`${pdfFileName}.pdf`);
    } else {
      console.error(`Element with id ${elementId} not found`);
    }
  } catch (error) {
    console.error("Error generating PDF:", error);
  } finally {
    setLoading(false);
  }
};
