import { jsPDF } from "jspdf";
import "jspdf-autotable";
import { reportDateFormatter } from './reportTimezoneFormatter';
import { cleanText } from '@/lib/pdfTextUtils';

export const generateCollectionReport = (collections, statusFilter = 'active', clientName = 'Association') => {
  // 1. Initialize Document
  const doc = new jsPDF({
    orientation: "landscape",
    unit: "pt", 
    format: "letter" 
  });
  doc.setCharSpace(0); // Fix spacing

  // Updated Margins: 0.25 inch = 18 pts
  const margin = 18; 
  const pageWidth = doc.internal.pageSize.getWidth();
  const pageHeight = doc.internal.pageSize.getHeight();
  const today = reportDateFormatter.shortDate(new Date()); // Use EST date

  // Helper to filter data logic: Resolved vs Active
  const isResolved = (c) => {
    const status = (c.status || '').toLowerCase();
    return status === 'resolved';
  };

  let filteredCollections = [];
  if (statusFilter === 'active') {
    filteredCollections = collections.filter(c => !isResolved(c));
  } else if (statusFilter === 'resolved') {
    filteredCollections = collections.filter(c => isResolved(c));
  } else {
    filteredCollections = collections;
  }

  let finalSections = [];
  
  if (statusFilter === 'active') {
     finalSections.push({ title: "ACTIVE COLLECTION CASES - FINANCIAL REPORT", data: filteredCollections, color: [59, 130, 246] }); // Blue
  } else if (statusFilter === 'resolved') {
     finalSections.push({ title: "RESOLVED COLLECTION CASES - FINANCIAL REPORT", data: filteredCollections, color: [34, 197, 94] }); // Green
  } else {
     const activeCases = filteredCollections.filter(c => !isResolved(c));
     const resolvedCases = filteredCollections.filter(c => isResolved(c));
     if (activeCases.length > 0) finalSections.push({ title: "ACTIVE COLLECTION CASES - FINANCIAL REPORT", data: activeCases, color: [59, 130, 246] });
     if (resolvedCases.length > 0) finalSections.push({ title: "RESOLVED COLLECTION CASES - FINANCIAL REPORT", data: resolvedCases, color: [34, 197, 94] });
  }

  let yPos = margin;

  // Header Drawing Function
  const drawHeader = () => {
    doc.setFontSize(14); 
    doc.setFont("helvetica", "bold");
    doc.setTextColor(30, 41, 59); 
    doc.text(cleanText((clientName || 'Report').toUpperCase()), margin, margin + 10);
    
    doc.setFontSize(9); 
    doc.setFont("helvetica", "normal");
    doc.setTextColor(100, 116, 139); 
    doc.text("Collection Financial Report", margin, margin + 22);
    
    doc.text(`Generated: ${today} (EST)`, pageWidth - margin, margin + 10, { align: 'right' });
    
    const typeLabel = statusFilter.charAt(0).toUpperCase() + statusFilter.slice(1);
    doc.text(`Report Type: ${cleanText(typeLabel)}`, pageWidth - margin, margin + 22, { align: 'right' });
    
    doc.setDrawColor(203, 213, 225);
    doc.setLineWidth(1);
    doc.line(margin, margin + 30, pageWidth - margin, margin + 30);
    
    return margin + 45; 
  };

  const drawFooter = (data) => {
    // const pageCount = doc.internal.getNumberOfPages(); // unused
    doc.setFontSize(7); 
    doc.setTextColor(148, 163, 184); 
    doc.text(`Page ${data.pageNumber}`, pageWidth - margin, pageHeight - 10, { align: 'right' });
    doc.text("Confidential - Generated by Horizons System", margin, pageHeight - 10);
  };

  yPos = drawHeader();

  console.log("Generating report with columns: Address, Amount Due, Deadline, Status, Assessments, Interest, Late Fees, Admin Fees, Legal Fees. (Stage excluded, EST Dates)");

  finalSections.forEach((section, index) => {
    const isFirst = index === 0;
    
    if (!isFirst) {
      doc.addPage();
      yPos = drawHeader();
    }

    doc.setFontSize(11);
    doc.setFont("helvetica", "bold");
    doc.setTextColor(...section.color);
    doc.text(cleanText(section.title), margin, yPos);
    yPos += 15; 

    if (section.data.length > 0) {
      const totalAmount = section.data.reduce((sum, c) => {
         const val = c.amount_due ? Number(c.amount_due) : ((Number(c.assessments_due)||0) + (Number(c.interest_due)||0) + (Number(c.late_fees_due)||0) + (Number(c.admin_fees_due)||0) + (Number(c.legal_fees_due)||0));
         return sum + val;
      }, 0);
      
      doc.setFillColor(248, 250, 252);
      doc.rect(margin, yPos - 10, pageWidth - (margin * 2), 20, 'F');
      
      doc.setFontSize(9);
      doc.setTextColor(51, 65, 85);
      doc.setFont("helvetica", "bold");
      doc.text(`Total Cases: ${section.data.length}`, margin + 8, yPos + 3);
      doc.text(`Total Outstanding: $${totalAmount.toFixed(2)}`, margin + 120, yPos + 3);
      yPos += 20;

      const tableHeaders = [[
        'Property Address', 
        'Amount Due', 
        'Deadline', 
        'Status', 
        'Assessments', 
        'Interest', 
        'Late Fees', 
        'Admin Fees', 
        'Legal Fees'
      ]];

      const tableBody = section.data.map(c => {
        const total = c.amount_due ? Number(c.amount_due) : ((Number(c.assessments_due)||0) + (Number(c.interest_due)||0) + (Number(c.late_fees_due)||0) + (Number(c.admin_fees_due)||0) + (Number(c.legal_fees_due)||0));
        
        const address = c.address || c.property_owners?.property_address || 'N/A';
        // Use report date formatter for EST dates
        const deadlineVal = c.due_date ? reportDateFormatter.shortDate(c.due_date) : '-';
        
        return [
          cleanText(address),
          `$${total.toFixed(2)}`,
          deadlineVal,
          cleanText(c.status || 'Active'),
          `$${(Number(c.assessments_due)||0).toFixed(2)}`,
          `$${(Number(c.interest_due)||0).toFixed(2)}`,
          `$${(Number(c.late_fees_due)||0).toFixed(2)}`,
          `$${(Number(c.admin_fees_due)||0).toFixed(2)}`,
          `$${(Number(c.legal_fees_due)||0).toFixed(2)}`
        ];
      });

      doc.autoTable({
        startY: yPos,
        head: tableHeaders,
        body: tableBody,
        theme: 'striped',
        styles: {
          fontSize: 8,
          cellPadding: 8,
          valign: 'middle',
          overflow: 'linebreak'
        },
        headStyles: {
          fillColor: section.color,
          textColor: [255, 255, 255],
          fontStyle: 'bold',
          halign: 'left',
          fontSize: 8 
        },
        columnStyles: {
          0: { cellWidth: 160 }, // Address
          1: { cellWidth: 75, halign: 'right', fontStyle: 'bold' }, // Amount Due
          2: { cellWidth: 70, halign: 'center' }, // Deadline
          3: { cellWidth: 75 }, // Status
          4: { cellWidth: 70, halign: 'right' }, // Assessments
          5: { cellWidth: 70, halign: 'right' }, // Interest
          6: { cellWidth: 70, halign: 'right' }, // Late Fees
          7: { cellWidth: 70, halign: 'right' }, // Admin Fees
          8: { cellWidth: 70, halign: 'right' }, // Legal Fees
        },
        margin: { top: margin, right: margin, bottom: margin + 15, left: margin },
        didDrawPage: drawFooter
      });
      
      yPos = doc.lastAutoTable.finalY + 25;

    } else {
      doc.setFontSize(9);
      doc.setTextColor(148, 163, 184);
      doc.setFont("helvetica", "italic");
      doc.text("No records found in this category.", margin, yPos);
      yPos += 30;
    }
  });

  const filename = `${cleanText(clientName).replace(/[^a-z0-9]/gi, '_')}_Financial_Report_${statusFilter}_${new Date().toISOString().split('T')[0]}.pdf`;
  doc.save(filename);
};