import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import SubaLogo from "../../../public/assets/SUBAlogo.png"

interface PDFOptions {
  title?: string;
  subtitle?: string;
  fileName?: string;
  logoUrl?: string;
  brandName?: string;
  themeColor?: [number, number, number];
}

export const downloadPDF = async (
  columns: string[],
  rows: (string | number)[][],
  options?: PDFOptions
) => {
  const doc = new jsPDF();
  const {
    title = "Report",
    subtitle = "",
    fileName = "report",
    logoUrl = SubaLogo.src,
    brandName = "SubaCapital",
    themeColor = [100, 99, 255],
  } = options || {};

  // 🖼️ Add Logo (optional)
  const img = new Image();
  img.src = logoUrl;
  await new Promise((resolve) => (img.onload = resolve));

  const pageWidth = doc.internal.pageSize.getWidth();
  const logoWidth = 20;
  const logoHeight = 20;
  const logoX = (pageWidth - logoWidth) / 2;

  doc.addImage(img, "PNG", logoX, 10, logoWidth, logoHeight);

  // 🟣 Brand Header
  doc.setFontSize(18);
  doc.setTextColor(...themeColor);
  doc.text(brandName, pageWidth / 2, 50, { align: "center" });

  doc.setFontSize(12);
  doc.setTextColor(40);
  doc.text(title, pageWidth / 2, 58, { align: "center" });
  if (subtitle) doc.text(subtitle, pageWidth / 2, 65, { align: "center" });

  // ✅ Use new autoTable syntax
  autoTable(doc, {
    startY: subtitle ? 75 : 70,
    head: [columns],
    body: rows,
    theme: "grid",
    headStyles: {
      fillColor: themeColor,
      textColor: [255, 255, 255],
      fontStyle: "bold",
    },
    styles: {
      fontSize: 10,
      cellPadding: 3,
      halign: "center",
    },
    alternateRowStyles: { fillColor: [245, 245, 245] },
  });

  // 📅 Footer
  const date = new Date().toLocaleString();
  doc.setFontSize(10);
  doc.setTextColor(100);
  doc.text(`Generated on ${date}`, 14, doc.internal.pageSize.getHeight() - 12);
  doc.text(
    `© ${brandName} — Makes growing wealth easy`,
    pageWidth / 2,
    doc.internal.pageSize.getHeight() - 6,
    { align: "center" }
  );

  // 💾 Save File
  doc.save(`${fileName}-${new Date().toISOString().split("T")[0]}.pdf`);
  
};