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

/**
 * Simple currency formatter fallback
 */
function formatCurrency(val) {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(val || 0);
}

/**
 * Generates an Owner Statement PDF for a specific unit and its transactions.
 */
export async function generateOwnerStatementPDF({ unit, transactions }) {
  if (!jsPDF) {
    throw new Error('PDF generation library (jsPDF) is not available.');
  }

  try {
    const doc = new jsPDF({
      orientation: 'portrait',
      unit: 'pt',
      format: 'letter'
    });

    const primaryColor = [30, 58, 138];
    const secondaryColor = [100, 116, 139];
    const margin = 40;
    let currentY = margin;
    const pageWidth = doc.internal.pageSize.getWidth();

    const sortedTx = [...transactions].sort((a, b) => {
      const d1 = new Date(a.transaction_date).getTime();
      const d2 = new Date(b.transaction_date).getTime();
      if (d1 !== d2) return d1 - d2;
      return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
    });

    let runningBalance = 0;
    let totalCharges = 0;
    let totalPayments = 0;

    const tableData = sortedTx.map(t => {
      const isVoided = t.status === 'voided';
      const isDebit = t.debit_credit === 'debit';
      const amt = parseFloat(t.amount || 0);
      
      if (!isVoided) {
        if (isDebit) {
          runningBalance += amt;
          totalCharges += amt;
        } else {
          runningBalance -= amt;
          totalPayments += amt;
        }
      }

      let desc = t.description || '';
      if (isVoided) desc = `[VOIDED] ${desc}`;
      
      return [
        t.transaction_date ? format(new Date(t.transaction_date), 'MM/dd/yyyy') : '-',
        desc,
        isDebit ? 'Charge' : 'Payment',
        isVoided ? '$0.00' : (isDebit ? formatCurrency(amt) : `(${formatCurrency(amt)})`),
        formatCurrency(runningBalance)
      ];
    });

    // Header
    doc.setFontSize(20);
    doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
    doc.setFont('helvetica', 'bold');
    doc.text('Owner Statement', margin, currentY);
    
    doc.setFontSize(10);
    doc.setTextColor(secondaryColor[0], secondaryColor[1], secondaryColor[2]);
    doc.setFont('helvetica', 'normal');
    const statementDate = `Statement Date: ${format(new Date(), 'MM/dd/yyyy')}`;
    doc.text(statementDate, pageWidth - margin, currentY, { align: 'right' });
    
    currentY += 25;

    doc.setFontSize(14);
    doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
    doc.setFont('helvetica', 'bold');
    doc.text(unit?.clients?.name || 'Association', margin, currentY);
    
    currentY += 20;

    doc.setDrawColor(226, 232, 240);
    doc.setFillColor(248, 250, 252);
    doc.roundedRect(margin, currentY, pageWidth - (margin * 2), 70, 4, 4, 'FD');

    currentY += 15;
    doc.setFontSize(10);
    
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
    doc.text('Owner Name:', margin + 10, currentY);
    doc.setFont('helvetica', 'normal');
    doc.setTextColor(secondaryColor[0], secondaryColor[1], secondaryColor[2]);
    doc.text(unit?.owner_name || 'N/A', margin + 85, currentY);
    
    currentY += 15;
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
    doc.text('Property:', margin + 10, currentY);
    doc.setFont('helvetica', 'normal');
    doc.setTextColor(secondaryColor[0], secondaryColor[1], secondaryColor[2]);
    doc.text(unit?.property_address || 'N/A', margin + 85, currentY);

    currentY -= 15;
    const midPoint = pageWidth / 2;
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
    doc.text('Account No:', midPoint, currentY);
    doc.setFont('helvetica', 'normal');
    doc.setTextColor(secondaryColor[0], secondaryColor[1], secondaryColor[2]);
    doc.text(unit?.account_number || 'N/A', midPoint + 70, currentY);
    
    currentY += 15;
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
    doc.text('Unit ID:', midPoint, currentY);
    doc.setFont('helvetica', 'normal');
    doc.setTextColor(secondaryColor[0], secondaryColor[1], secondaryColor[2]);
    doc.text(unit?.unit_id || 'N/A', midPoint + 70, currentY);

    currentY += 50;

    // Table
    doc.autoTable({
      startY: currentY,
      head: [['Date', 'Description', 'Type', 'Amount', 'Balance']],
      body: tableData,
      theme: 'grid',
      headStyles: {
        fillColor: [241, 245, 249],
        textColor: [15, 23, 42],
        fontStyle: 'bold',
        halign: 'left'
      },
      columnStyles: {
        0: { cellWidth: 70 },
        1: { cellWidth: 'auto' },
        2: { cellWidth: 60 },
        3: { cellWidth: 80, halign: 'right' },
        4: { cellWidth: 80, halign: 'right', fontStyle: 'bold' }
      },
      styles: {
        fontSize: 9,
        cellPadding: 6,
        lineColor: [226, 232, 240],
        textColor: [51, 65, 85]
      },
      alternateRowStyles: {
        fillColor: [250, 250, 250]
      },
      margin: { left: margin, right: margin }
    });

    currentY = doc.lastAutoTable.finalY + 30;

    // Summary
    if (currentY + 100 > doc.internal.pageSize.getHeight() - margin) {
      doc.addPage();
      currentY = margin;
    }

    doc.setFontSize(12);
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
    doc.text('Account Summary', margin, currentY);
    
    currentY += 10;
    doc.setDrawColor(226, 232, 240);
    doc.line(margin, currentY, pageWidth - margin, currentY);
    
    currentY += 15;
    doc.setFontSize(10);
    doc.setFont('helvetica', 'normal');
    doc.setTextColor(secondaryColor[0], secondaryColor[1], secondaryColor[2]);
    
    const summaryColWidth = 150;
    
    doc.text('Total Charges:', margin, currentY);
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
    doc.text(formatCurrency(totalCharges), margin + 100, currentY, { align: 'right' });
    
    doc.setFont('helvetica', 'normal');
    doc.setTextColor(secondaryColor[0], secondaryColor[1], secondaryColor[2]);
    doc.text('Total Payments:', margin + summaryColWidth, currentY);
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
    doc.text(formatCurrency(totalPayments), margin + summaryColWidth + 100, currentY, { align: 'right' });

    doc.setFont('helvetica', 'bold');
    doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
    doc.text('Ending Balance:', margin + (summaryColWidth * 2), currentY);
    
    const dbBalance = parseFloat(unit?.balance || 0);
    doc.text(formatCurrency(dbBalance), margin + (summaryColWidth * 2) + 100, currentY, { align: 'right' });

    // Footer
    const pageCount = doc.internal.getNumberOfPages();
    for (let i = 1; i <= pageCount; i++) {
      doc.setPage(i);
      doc.setFontSize(8);
      doc.setTextColor(148, 163, 184);
      doc.text(
        `Generated by Avria Cloud on ${format(new Date(), 'MMM dd, yyyy HH:mm a')}`,
        margin,
        doc.internal.pageSize.getHeight() - 20
      );
      doc.text(
        `Page ${i} of ${pageCount}`,
        pageWidth - margin,
        doc.internal.pageSize.getHeight() - 20,
        { align: 'right' }
      );
    }

    const safeName = (unit?.owner_name || unit?.unit_id || 'Unit').replace(/[^a-z0-9]/gi, '_');
    const dateStr = format(new Date(), 'yyyy-MM-dd');
    const fileName = `OwnerStatement_${safeName}_${dateStr}.pdf`;
    
    doc.save(fileName);
    return Promise.resolve();

  } catch (error) {
    console.error('Error in generateOwnerStatementPDF:', error);
    throw error;
  }
}
