import { jsPDF } from "jspdf";
import autoTable from "jspdf-autotable";

const formatCurrency = (val) => {
  if (val < 0) return `-$${Math.abs(val).toFixed(2)}`;
  return `$${val.toFixed(2)}`;
};

export const exportLedgerStatementPdf = ({ ledgerName, clientAssociation, propertyOwner, interestRate, rows, totals, totalDue }) => {
  if (!rows || rows.length === 0) {
    throw new Error("No ledger entries to export.");
  }

  const doc = new jsPDF({ unit: "pt", format: "letter" });
  const m = 40;
  const pageW = doc.internal.pageSize.getWidth();

  // Header
  doc.setFont("helvetica", "bold");
  doc.setFontSize(10);
  doc.text("ACCOUNT HOLDER:", m, m + 10);
  doc.setFont("helvetica", "normal");
  doc.text(propertyOwner || "N/A", m, m + 22);

  doc.setFont("helvetica", "bold");
  doc.text("PROPERTY ADDRESS:", m, m + 42);
  doc.setFont("helvetica", "normal");
  doc.text("N/A", m, m + 54);

  // Title right side
  doc.setFont("helvetica", "bold");
  doc.setFontSize(18);
  doc.text("ACCOUNT STATEMENT", pageW - m, m + 10, { align: "right" });
  doc.setFont("helvetica", "normal");
  doc.setFontSize(9);
  const today = new Date();
  doc.text(`Statement Date: ${today.getMonth() + 1}/${today.getDate()}/${today.getFullYear()}`, pageW - m, m + 26, { align: "right" });
  doc.text(`Association: ${clientAssociation || "N/A"}`, pageW - m, m + 38, { align: "right" });

  const startY = m + 75;

  // Amounts Due Breakdown table (left)
  const breakdownData = [
    ["Assessments", formatCurrency(totals.assess)],
    ["Late Fees", formatCurrency(totals.late)],
    ["Admin Fees", formatCurrency(totals.admin)],
    ["Legal Fees", formatCurrency(totals.legal)],
    ["Violations", formatCurrency(totals.viol)],
    [`Interest @ ${(parseFloat(interestRate) / 12).toFixed(2)}%`, formatCurrency(totals.interest)],
    ["Bank Fees", formatCurrency(totals.bank)],
  ];

  autoTable(doc, {
    startY,
    head: [["Amounts Due Breakdown", "Amount"]],
    body: breakdownData,
    theme: "grid",
    styles: { fontSize: 8, cellPadding: 4 },
    headStyles: { fillColor: [0, 0, 0], textColor: 255, fontStyle: "bold" },
    columnStyles: { 1: { halign: "right" } },
    margin: { left: m, right: pageW / 2 + 20 },
    tableWidth: (pageW / 2) - m - 30,
  });

  // Account summary table (right)
  autoTable(doc, {
    startY,
    head: [["Account Number", "Due Date", "Total Due"]],
    body: [["N/A", "Upon Receipt", formatCurrency(totalDue)]],
    theme: "grid",
    styles: { fontSize: 8, cellPadding: 4 },
    headStyles: { fillColor: [0, 0, 0], textColor: 255, fontStyle: "bold" },
    columnStyles: { 2: { halign: "right", fontStyle: "bold" } },
    margin: { left: pageW / 2 + 20, right: m },
    tableWidth: (pageW / 2) - m - 30,
  });

  // Main ledger table
  const ledgerStartY = Math.max(doc.lastAutoTable?.finalY || startY + 120, startY + 120) + 25;
  const columns = ["Date", "Description", "Assess", "Late", "Admin", "Legal", "Viol", "Int", "Bank", "Pay (AR)", "Balance"];

  const bodyData = rows.map(r => [
    r.date,
    r.description,
    formatCurrency(r.assess || 0),
    formatCurrency(r.late || 0),
    formatCurrency(r.admin || 0),
    formatCurrency(r.legal || 0),
    formatCurrency(r.viol || 0),
    formatCurrency(r.interest || 0),
    formatCurrency(r.bank || 0),
    formatCurrency(r.payAR || 0),
    formatCurrency(r.balance),
  ]);

  // Totals row
  bodyData.push([
    "TOTALS", "",
    formatCurrency(totals.assess),
    formatCurrency(totals.late),
    formatCurrency(totals.admin),
    formatCurrency(totals.legal),
    formatCurrency(totals.viol),
    formatCurrency(totals.interest),
    formatCurrency(totals.bank),
    formatCurrency(totals.payAR),
    formatCurrency(totalDue),
  ]);

  autoTable(doc, {
    startY: ledgerStartY,
    head: [columns],
    body: bodyData,
    theme: "grid",
    styles: { fontSize: 7, cellPadding: 3 },
    headStyles: { fillColor: [0, 0, 0], textColor: 255, fontStyle: "bold" },
    columnStyles: {
      0: { cellWidth: 60 },
      1: { cellWidth: 90 },
      2: { halign: "right" },
      3: { halign: "right" },
      4: { halign: "right" },
      5: { halign: "right" },
      6: { halign: "right" },
      7: { halign: "right" },
      8: { halign: "right" },
      9: { halign: "right", textColor: [34, 139, 34] },
      10: { halign: "right", fontStyle: "bold" },
    },
    margin: { left: m, right: m },
    didParseCell: (data) => {
      // Bold totals row
      if (data.row.index === bodyData.length - 1) {
        data.cell.styles.fontStyle = "bold";
      }
    },
  });

  // Footer
  const pageH = doc.internal.pageSize.getHeight();
  doc.setFont("helvetica", "normal");
  doc.setFontSize(7);
  doc.setTextColor(130, 130, 130);
  const footerText = `Generated by Avria Community Management • Page 1 of 1 • Printed on ${today.toLocaleDateString()} ${today.toLocaleTimeString()}`;
  doc.text(footerText, pageW / 2, pageH - 20, { align: "center" });

  const safeName = ledgerName ? ledgerName.replace(/\s+/g, "-") : "ledger";
  doc.save(`account-statement-${safeName}-${today.toISOString().split("T")[0]}.pdf`);
};
