import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import { format } from "date-fns";

interface CollectionRow {
  ownerName: string;
  unitNumber: string;
  association: string;
  balance: number;
  stage: string;
  daysDelinquent: number;
  lastNoticeDate: string | null;
  assessments: number;
  lateFees: number;
  interest: number;
  legalFees: number;
  adminFees: number;
  violations: number;
  bankFees: number;
  payments: number;
}

export function exportCollectionsPdf(
  rows: CollectionRow[],
  title = "Collections Report"
) {
  const doc = new jsPDF({ orientation: "landscape" });
  const now = format(new Date(), "MMM d, yyyy h:mm a");

  doc.setFontSize(18);
  doc.text(title, 14, 20);
  doc.setFontSize(9);
  doc.setTextColor(100);
  doc.text(`Generated: ${now}  •  ${rows.length} accounts`, 14, 27);
  doc.setTextColor(0);

  const totalBalance = rows.reduce((s, r) => s + r.balance, 0);
  const totalAssessments = rows.reduce((s, r) => s + r.assessments, 0);
  const totalLateFees = rows.reduce((s, r) => s + r.lateFees, 0);
  const totalInterest = rows.reduce((s, r) => s + r.interest, 0);
  const totalLegal = rows.reduce((s, r) => s + r.legalFees, 0);
  const totalAdmin = rows.reduce((s, r) => s + r.adminFees, 0);
  const totalViolations = rows.reduce((s, r) => s + r.violations, 0);
  const totalBankFees = rows.reduce((s, r) => s + r.bankFees, 0);
  const totalPayments = rows.reduce((s, r) => s + r.payments, 0);

  doc.setFontSize(10);
  doc.text(`Total Outstanding: $${totalBalance.toLocaleString(undefined, { minimumFractionDigits: 2 })}`, 14, 34);

  const fmt = (n: number) =>
    "$" + n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  autoTable(doc, {
    startY: 40,
    head: [[
      "Owner", "Unit", "Association", "Stage", "Days",
      "Assessments", "Late Fees", "Interest", "Legal", "Admin", "Violations", "Bank Fees", "Payments", "Balance", "Last Notice"
    ]],
    body: rows.map((r) => [
      r.ownerName,
      r.unitNumber || "—",
      r.association,
      r.stage,
      String(r.daysDelinquent),
      fmt(r.assessments),
      fmt(r.lateFees),
      fmt(r.interest),
      fmt(r.legalFees),
      fmt(r.adminFees),
      fmt(r.violations),
      fmt(r.bankFees),
      r.payments > 0 ? `-${fmt(r.payments)}` : fmt(0),
      fmt(r.balance),
      r.lastNoticeDate ? format(new Date(r.lastNoticeDate), "MM/dd/yyyy") : "—",
    ]),
    foot: [[
      "TOTALS", "", "", "", "",
      fmt(totalAssessments),
      fmt(totalLateFees),
      fmt(totalInterest),
      fmt(totalLegal),
      fmt(totalAdmin),
      fmt(totalViolations),
      fmt(totalBankFees),
      totalPayments > 0 ? `-${fmt(totalPayments)}` : fmt(0),
      fmt(totalBalance),
      "",
    ]],
    styles: { fontSize: 6, cellPadding: 1.5 },
    headStyles: { fillColor: [59, 130, 246], fontSize: 6 },
    footStyles: { fillColor: [240, 240, 240], textColor: [0, 0, 0], fontStyle: "bold", fontSize: 6 },
    alternateRowStyles: { fillColor: [245, 247, 250] },
    columnStyles: {
      5: { halign: "right" },
      6: { halign: "right" },
      7: { halign: "right" },
      8: { halign: "right" },
      9: { halign: "right" },
      10: { halign: "right" },
      11: { halign: "right" },
      12: { halign: "right" },
      13: { halign: "right" },
    },
    didDrawPage: (data: any) => {
      const pageCount = doc.getNumberOfPages();
      doc.setFontSize(7);
      doc.setTextColor(150);
      doc.text(
        `Page ${data.pageNumber} of ${pageCount}`,
        doc.internal.pageSize.width - 30,
        doc.internal.pageSize.height - 8
      );
    },
  });

  doc.save(`Collections_Report_${format(new Date(), "yyyy-MM-dd")}.pdf`);
}
