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

/**
 * Generate an approval or denial letter PDF for an ARC application.
 * @param {object} params
 * @param {'approved'|'denied'} params.decision
 * @param {object} params.application - ARC application row (with joined owners, units, associations)
 * @param {string} [params.decisionNotes]
 */
export function generateArcDecisionLetterPdf({ decision, application, decisionNotes }) {
  if (!application) return;
  const isApproved = decision === 'approved';
  const doc = new jsPDF({ unit: 'pt', format: 'letter' });

  const pageWidth = doc.internal.pageSize.getWidth();
  const pageHeight = doc.internal.pageSize.getHeight();
  const margin = 72; // 1 inch
  let y = margin;

  const associationName = application.associations?.name || 'Homeowners Association';
  const ownerName = application.owners
    ? `${application.owners.first_name || ''} ${application.owners.last_name || ''}`.trim()
    : 'Homeowner';
  const propertyAddress =
    application.units?.address ||
    application.owners?.property_address ||
    application.units?.unit_number ||
    '';
  const today = format(new Date(), 'MMMM d, yyyy');
  const projectTitle = application.title || 'Architectural review request';
  const projectType = application.project_type || '';

  // Header — association name
  doc.setFont('times', 'bold');
  doc.setFontSize(16);
  doc.text(associationName, pageWidth / 2, y, { align: 'center' });
  y += 18;
  doc.setFont('times', 'normal');
  doc.setFontSize(11);
  doc.text('Architectural Review Committee', pageWidth / 2, y, { align: 'center' });
  y += 28;

  // Date
  doc.setFontSize(11);
  doc.text(today, margin, y);
  y += 28;

  // Recipient block
  doc.text(ownerName, margin, y);
  y += 14;
  if (propertyAddress) {
    const lines = doc.splitTextToSize(propertyAddress, pageWidth - margin * 2);
    lines.forEach((line) => { doc.text(line, margin, y); y += 14; });
  }
  y += 14;

  // Subject
  doc.setFont('times', 'bold');
  doc.text(`Re: ARC Application — ${projectTitle}${projectType ? ` (${projectType})` : ''}`, margin, y);
  y += 22;

  // Salutation
  doc.setFont('times', 'normal');
  doc.text(`Dear ${ownerName || 'Homeowner'},`, margin, y);
  y += 22;

  // Body
  const paragraphs = isApproved
    ? [
        `We are pleased to inform you that the Architectural Review Committee of ${associationName} has APPROVED your application referenced above${propertyAddress ? ` for the property located at ${propertyAddress}` : ''}.`,
        decisionNotes
          ? `The Committee's notes regarding this approval are as follows:`
          : `Please ensure that all work performed conforms to the plans submitted with your application as well as the governing documents of the Association.`,
      ]
    : [
        `After careful review, the Architectural Review Committee of ${associationName} was unable to approve your application referenced above${propertyAddress ? ` for the property located at ${propertyAddress}` : ''}. Your application has been DENIED.`,
        decisionNotes
          ? `The Committee's reasons for this decision are as follows:`
          : `You may submit a revised application addressing the Committee's concerns. Please contact the management office if you have any questions about this decision.`,
      ];

  doc.setFontSize(11);
  paragraphs.forEach((p) => {
    const lines = doc.splitTextToSize(p, pageWidth - margin * 2);
    lines.forEach((line) => {
      if (y > pageHeight - margin - 60) { doc.addPage(); y = margin; }
      doc.text(line, margin, y);
      y += 14;
    });
    y += 8;
  });

  // Decision notes block
  if (decisionNotes && decisionNotes.trim()) {
    if (y > pageHeight - margin - 80) { doc.addPage(); y = margin; }
    doc.setFont('times', 'italic');
    const noteLines = doc.splitTextToSize(decisionNotes.trim(), pageWidth - margin * 2 - 24);
    // Indent block
    noteLines.forEach((line) => {
      if (y > pageHeight - margin - 40) { doc.addPage(); y = margin; }
      doc.text(line, margin + 24, y);
      y += 14;
    });
    y += 10;
    doc.setFont('times', 'normal');
  }

  // Closing
  if (y > pageHeight - margin - 100) { doc.addPage(); y = margin; }
  const closing = isApproved
    ? `Please retain this letter for your records. If you have any questions, please contact the management office.`
    : `If you wish to submit a revised application, please do so through the homeowner portal. We appreciate your cooperation.`;
  const closingLines = doc.splitTextToSize(closing, pageWidth - margin * 2);
  closingLines.forEach((line) => { doc.text(line, margin, y); y += 14; });
  y += 28;

  doc.text('Sincerely,', margin, y);
  y += 50;
  doc.text('Architectural Review Committee', margin, y);
  y += 14;
  doc.text(associationName, margin, y);

  const safeTitle = (projectTitle || 'arc').replace(/[^a-z0-9]+/gi, '-').toLowerCase();
  const fileName = `arc-${decision}-letter-${safeTitle}.pdf`;
  doc.save(fileName);
}
