// import React from 'react';
import pdfMake from "pdfmake/build/pdfmake";
import pdfFonts from "pdfmake/build/vfs_fonts";

// Properly assign the vfs property to avoid "undefined" errors
pdfMake.vfs = pdfFonts?.pdfMake?.vfs;

const PDFGenerator = () => {
  const handleDownload = () => {
    const dynamicContent = "This is the conditional content for the last page.";

    const documentDefinition = {
      pageSize: "A4",
      pageMargins: [40, 80, 40, 60], // [left, top, right, bottom]

      header: (currentPage: number, pageCount: number) => ({
        columns: [
          { text: "Header Text", alignment: "left", margin: [20, 10] },
          {
            text: `Page ${currentPage} of ${pageCount}`,
            alignment: "right",
            margin: [20, 10],
          },
        ],
      }),

      footer: () => ({
        columns: [
          // { text: "Footer Text", alignment: "center", margin: [0, 10] },
          {
            image: "footerImage",
            width: 500,
            alignment: "center",
            margin: [0, 5],
          },
        ],
      }),

      background: () => ({
        image: "sealImage",
        width: 100,
        absolutePosition: { x: 250, y: 400 },
        opacity: 0.2,
      }),

      content: [
        { text: "Larger Content", style: "header" },
        "This is an example of a long content page in the PDF document. ",
        {
          text: "Repeated Content ".repeat(950), // Simulate large content
        },
        {
          text: dynamicContent,
          style: "subheader",
          pageBreak: "auto",
        },
      ],

      pageBreakBefore: (
        // currentNode: any,
        followingNodesOnPage: any[]
        // nodesOnNextPage: any[],
        // previousNodesOnPage: any[]
      ) => {
        const lastNodeOnPage =
          followingNodesOnPage[followingNodesOnPage.length - 1];
        if (lastNodeOnPage && lastNodeOnPage.id === "conditionalContent") {
          return true; // Forces a page break if not enough space
        }
        return false;
      },

      images: {
        footerImage:
          "https://fastly.picsum.photos/id/841/536/354.jpg?hmac=9OJRC9APLWDSoNYQJSkqlspSeFdCCY8rjrnH3S5O41g",
        sealImage:
          "https://fastly.picsum.photos/id/841/536/354.jpg?hmac=9OJRC9APLWDSoNYQJSkqlspSeFdCCY8rjrnH3S5O41g",
      },

      styles: {
        header: { fontSize: 18, bold: true, margin: [0, 20, 0, 10] },
        subheader: { fontSize: 15, margin: [0, 15, 0, 5] },
      },
    };

    (pdfMake as any).createPdf(documentDefinition).download("example.pdf");
  };

  return <button onClick={handleDownload}>Download PDF</button>;
};

export default PDFGenerator;
