import jsPDF from 'jspdf';
import 'jspdf-autotable';

export const generateFinancialReportPDF = (reportData, clientName, asOfDate) => {
  const doc = new jsPDF();
  
  doc.setFontSize(18);
  doc.text('Balance Sheet', 14, 22);
  doc.setFontSize(12);
  doc.text(clientName || 'Association', 14, 30);
  doc.setFontSize(10);
  doc.text(`As of ${new Date(asOfDate).toLocaleDateString()}`, 14, 36);

  // Note: Prepaid assessments and Payables are explicitly EXCLUDED from this report per business logic.
  // We only include Bank Accounts, Accounts Receivable, and calculated Equity.

  const totalAssets = reportData.assets.bankAccounts.reduce((sum, a) => sum + a.balance, 0) + reportData.assets.accountsReceivable;
  const totalLiabilities = 0; // Excluded payables and prepaid assessments
  const totalEquity = reportData.equity.operatingFund + reportData.equity.reserveFund;

  const formatCurrency = (amt) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amt);

  const tableData = [];
  
  tableData.push([{ content: 'Assets', colSpan: 2, styles: { fontStyle: 'bold', fillColor: [240, 240, 240] } }]);
  if (reportData.assets.bankAccounts.length === 0 && reportData.assets.accountsReceivable === 0) {
      tableData.push(['No asset records found', '']);
  } else {
      reportData.assets.bankAccounts.forEach(acc => {
          tableData.push([acc.account, formatCurrency(acc.balance)]);
      });
      tableData.push(['Accounts Receivable', formatCurrency(reportData.assets.accountsReceivable)]);
  }
  tableData.push([{ content: 'Total Assets', styles: { fontStyle: 'bold' } }, { content: formatCurrency(totalAssets), styles: { fontStyle: 'bold' } }]);
  
  tableData.push([{ content: '', colSpan: 2, styles: { minCellHeight: 5 } }]); // Spacer

  tableData.push([{ content: 'Liabilities', colSpan: 2, styles: { fontStyle: 'bold', fillColor: [240, 240, 240] } }]);
  tableData.push(['No liabilities (Payables and Prepaid Assessments excluded)', '']);
  tableData.push([{ content: 'Total Liabilities', styles: { fontStyle: 'bold' } }, { content: formatCurrency(totalLiabilities), styles: { fontStyle: 'bold' } }]);

  tableData.push([{ content: '', colSpan: 2, styles: { minCellHeight: 5 } }]); // Spacer

  tableData.push([{ content: 'Equity', colSpan: 2, styles: { fontStyle: 'bold', fillColor: [240, 240, 240] } }]);
  tableData.push(['Operating Fund Balance (Retained Earnings)', formatCurrency(reportData.equity.operatingFund)]);
  tableData.push(['Reserve Fund Balance', formatCurrency(reportData.equity.reserveFund)]);
  tableData.push([{ content: 'Total Equity', styles: { fontStyle: 'bold' } }, { content: formatCurrency(totalEquity), styles: { fontStyle: 'bold' } }]);

  doc.autoTable({
    startY: 45,
    head: [['Account', 'Balance']],
    body: tableData,
    theme: 'grid',
    headStyles: { fillColor: [66, 66, 66] }
  });

  doc.save(`Balance_Sheet_${clientName}_${asOfDate}.pdf`);
};