const statementBreakdown = (statementBreakdown) => {
  let html = ``;

  if (statementBreakdown && Array.isArray(statementBreakdown)) {
    for (const breakdown of statementBreakdown) {
      html += `
            <tr>
              <td style="font-size: .8rem"><strong>${
                breakdown?.order_reference_no ?? "N/A"
              }</strong></td>
              <td>${breakdown?.order_total_amount ?? "N/A"}</td>
              <td>${breakdown?.payments_total ?? "N/A"}</td>
              <td>${breakdown?.unpaid_balance ?? "N/A"}</td>
              <td>${breakdown?.date ?? "N/A"}</td>
              <td>${breakdown?.due_date ?? "N/A"}</td>
              <td>${breakdown?.date_delivered ?? "N/A"}</td>
              <td>${breakdown?.remarks ?? "N/A"}</td>
            </tr>
            <tr>
              <td colspan="8">
                <table class="order-details-table">
                  <thead>
                    <tr>
                      <th>Product Name</th>
                      <th>Quantity</th>
                    </tr>
                  </thead>
                  <tbody>
                    ${
                      Array.isArray(breakdown?.order_form_details)
                        ? breakdown.order_form_details
                            .map(
                              (detail) => `
                        <tr>
                          <td>${detail?.product?.menu ?? "N/A"}</td>
                          <td>${detail?.quantity ?? "N/A"}</td>
                        </tr>
                      `,
                            )
                            .join("")
                        : `<tr><td colspan="4">No order details available</td></tr>`
                    }
                  </tbody>
                </table>
              </td>
            </tr>
          `;
    }
  }

  return html;
};

const createStatementPDF = async (data, image, customerSoa = false) => {
  // Your HTML content
  const htmlContent = `
      <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>BuildCredit Statement of Account</title>
      <style>
        body {
          margin: 0;
          padding: 0;
          font-family: Arial, sans-serif;
          color: #333;
        }
        .header {
          display: flex;
          justify-content: space-between;
          padding: 20px;
          border-bottom: 3px solid #d32f2f; /* Red color */
        }
        .header-logo img {
          width: 150px;
          height: auto;
        }
        .header-detail {
          text-align: right;
          font-size: 12px;
        }
        .main-content {
          display: flex;
          flex-direction: column;
          align-items: center;
          padding: 20px;
          border-bottom: 2px solid #ddd;
        }
        .titles {
          text-align: center;
        }
        .titles h3,
        .titles h4 {
          margin: 0;
        }
        .titles h3 {
          color: #d32f2f; /* Red color */
          margin-bottom: 8px;
        }
        .titles h4 {
          color: #555;
        }
        .date-time {
          text-align: right;
          padding: 0 20px 20px;
          font-size: 12px;
        }
        .main-table,
        .order-breakdown-table {
          padding: 0 20px;
          margin-top: 20px;
        }
        table {
          width: 100%;
          border-collapse: collapse;
          font-size: 10px;
        }
        th,
        td {
          padding: 10px;
          font-size: 10px;
          text-align: left;
        }
        th:not(.order-details-table th) {
          background-color: #d32f2f; /* Red color */
          color: white;
          font-size: 10px;
        }
        .order-details-table {
          border-bottom: 2px solid black;
        }
        .order-details-table th {
          font-size: 10px;
        }
        tr:nth-child(even) {
          background-color: #f9f9f9;
        }
        .order-breakdown-table {
          page-break-before: always;
        }
    
        table tr {
          page-break-inside: avoid;
        }
        @page {
          margin: 20mm;
        }
        body {
          margin: 0;
        }
        table {
          table-layout: fixed;
          word-wrap: break-word;
        }
        th,
        td {
          padding: 5px;
        }
      </style>
    </head>
    <body>
      <header class="header">
        <div class="header-logo">
          <img src="data:image/jpeg;base64,${image}" alt="BuildCredit Logo" />
        </div>
        <div class="header-detail">
          <p>Branch Office: 1501 The Centerpoint</p>
          <p>Condo., Julia Vargas Ave., Ortigas Center,</p>
          <p>Pasig, Metro Manila</p>
        </div>
      </header>
    
      <div class="main-content">
        <div class="titles">
          <h3>BUILDCREDIT</h3>
          <h4>${customerSoa ? "CUSTOMER" : ""} STATEMENT OF ACCOUNT</h4>
        </div>
      </div>
    
      <div class="date-time">
        <p>Date and Time: ${data.dateNTime}</p>
      </div>
    
      <div class="main-table">
        <table>
          <thead>
            <tr>
              <th>Company Name</th>
              <th>Status</th>
              <th>Credit Terms</th>
              <th>Build Credit Limit</th>
              <th>Account Balance</th>
              <th>Available Line</th>
              <th>PDC Sent & Received</th>
              <th>Account Balance Less PDC</th>
              <th>Available Line Plus PDC (SAP)</th>
              <th>Unclaimed Order Amount</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>${data.companyName}</td>
              <td>${data.buildcreditStatus}</td>
              <td>${data.creditTerms}</td>
              <td>${data.creditLimit}</td>
              <td>${data.accountBalance}</td>
              <td>${data.availableLine}</td>
              <td>${data.pdcSent}</td>
              <td>${data.abLessPdc}</td>
              <td>${data.alPlusPdc}</td>
              <td>${data.toBeCollectedTotal}</td>
            </tr>
          </tbody>
        </table>
      </div>
    
      <div class="order-breakdown-table titles">
        <div class="main-content">
          <h4>Statement Breakdown</h4>
        </div>
        <table>
          <thead>
            <tr>
              <th>Reference Number</th>
              <th>Order Total Amount</th>
              <th>Total Payments Made</th>
              <th>Unpaid Balance</th>
              <th>Date</th>
              <th>Due Date</th>
              <th>Actual Date Delivered/Received</th>
              <th>Remarks</th>
            </tr>
          </thead>
          <tbody>
            ${statementBreakdown(data.statementBreakdown)}
          </tbody>
        </table>
      </div>
    </body>
    </html>
    
    `;

  return htmlContent;
};

const createStatementMultiplePDF = async (data, image) => {
  const htmlContent = `
  <!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>BuildCredit Statement of Account</title>
      <style>
        /* ===== Base Styles ===== */
        :root {
          --primary-color: #d32f2f;
          --secondary-color: #555;
          --light-gray: #f9f9f9;
          --border-color: #ddd;
          --header-bg: #f5f5f5;
        }
        
        body {
          margin: 0;
          padding: 0;
          font-family: 'Arial', sans-serif;
          color: #333;
          line-height: 1.4;
        }
        
        /* ===== Layout Styles ===== */
        .container {
          max-width: 100%;
          margin: 0 auto;
        }
        
        .header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 1.5rem;
          border-bottom: 3px solid var(--primary-color);
        }
        
        .header-logo img {
          width: 150px;
          height: auto;
        }
        
        .header-detail {
          text-align: right;
          font-size: 0.75rem;
          line-height: 1.4;
        }
        
        .document-title {
          text-align: center;
          padding: 1.5rem 0;
          border-bottom: 2px solid var(--border-color);
          margin-bottom: 1rem;
        }
        
        .timestamp {
          text-align: right;
          padding: 0 1.5rem 1rem;
          font-size: 0.75rem;
          color: var(--secondary-color);
        }
        
        /* ===== Customer Section Styles ===== */
        .customer-section {
          margin-bottom: 2.5rem;
          page-break-after: always;
        }
        
        .customer-section:last-child {
          page-break-after: avoid;
        }
        
        .customer-header {
          background-color: var(--header-bg);
          padding: 0.75rem 1.5rem;
          margin: 1.5rem 0 1rem;
          border-left: 4px solid var(--primary-color);
        }
        
        .customer-header h4 {
          margin: 0;
          color: var(--primary-color);
          font-size: 1rem;
        }
        
        /* ===== Table Styles ===== */
        .table-container {
          padding: 0 1.5rem;
          margin: 1rem 0;
          overflow-x: auto;
        }
        
        table {
          width: 100%;
          border-collapse: collapse;
          font-size: 0.75rem;
          table-layout: fixed;
          word-wrap: break-word;
        }
        
        th, td {
          padding: 0.5rem;
          border-bottom: 1px solid var(--border-color);
          text-align: left;
          vertical-align: top;
        }
        
        th {
          background-color: var(--primary-color);
          color: white;
          font-weight: 600;
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }
        
        tr:nth-child(even) {
          background-color: var(--light-gray);
        }
        
        /* ===== Statement Breakdown Styles ===== */
        .statement-title {
          text-align: center;
          margin: 1.5rem 0 0.5rem;
          color: var(--secondary-color);
        }
        
        .order-details-table {
          width: 100%;
          margin: 0.5rem 0;
        }
        
        .order-details-table th {
          background-color: #e0e0e0;
          color: #333;
          font-size: 0.7rem;
        }
        
        /* ===== Utility Classes ===== */
        .text-center {
          text-align: center;
        }
        
        .text-right {
          text-align: right;
        }
        
        .text-bold {
          font-weight: bold;
        }
        
        .text-primary {
          color: var(--primary-color);
        }
        
        /* ===== Print Styles ===== */
        @page {
          size: A4;
          margin: 20mm;
        }
        
        @media print {
          body {
            font-size: 11pt;
          }
          
          table {
            page-break-inside: avoid;
          }
          
          .customer-section {
            page-break-inside: avoid;
          }
        }
      </style>
    </head>
    <body>
      <div class="container">
        <header class="header">
          <div class="header-logo">
            <img src="data:image/jpeg;base64,${image}" alt="BuildCredit Logo" />
          </div>
          <div class="header-detail">
            <p>Branch Office: 1501 The Centerpoint</p>
            <p>Condo., Julia Vargas Ave., Ortigas Center,</p>
            <p>Pasig, Metro Manila</p>
          </div>
        </header>
        
        <div class="document-title">
          <h3 class="text-primary">BUILDCREDIT</h3>
          <h4>STATEMENT OF ACCOUNT (${data.area})</h4>
        </div>
        
        <div class="timestamp">
          <p>Generated on: ${data.dateNTime}</p>
        </div>
        
        ${renderCustomers(data.customers)}
      </div>
    </body>
  </html>
  `;

  return htmlContent;
};

const renderCustomers = (customers) => {
  if (!customers || !Array.isArray(customers)) return "";

  return customers
    .map(
      (customer) => `
    <section class="customer-section">
      <div class="customer-header">
        <h4>Customer: ${customer.companyName || "N/A"}</h4>
      </div>
      
      <div class="table-container">
        <table>
          <thead>
            <tr>
              <th width="15%">Company Name</th>
              <th width="10%">Status</th>
              <th width="10%">Credit Terms</th>
              <th width="12%">Credit Limit</th>
              <th width="12%">Account Balance</th>
              <th width="12%">Available Line</th>
              <th width="12%">PDC Sent/Received</th>
              <th width="9%">Balance Less PDC</th>
              <th width="8%">Line Plus PDC</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>${customer.companyName || "N/A"}</td>
              <td>${customer.buildcreditStatus || "N/A"}</td>
              <td>${customer.creditTerms || "N/A"}</td>
              <td class="text-right">${customer.creditLimit || "N/A"}</td>
              <td class="text-right">${customer.accountBalance || "N/A"}</td>
              <td class="text-right">${customer.availableLine || "N/A"}</td>
              <td class="text-right">${customer.pdcSent || "N/A"}</td>
              <td class="text-right">${customer.abLessPdc || "N/A"}</td>
              <td class="text-right">${customer.alPlusPdc || "N/A"}</td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <h4 class="statement-title">STATEMENT BREAKDOWN</h4>
      
      <div class="table-container">
        ${renderStatementBreakdown(customer.statementBreakdown)}
      </div>
    </section>
  `,
    )
    .join("");
};

const renderStatementBreakdown = (breakdowns) => {
  if (!breakdowns || !Array.isArray(breakdowns))
    return "<p>No statement breakdown available</p>";

  return `
    <table>
      <thead>
        <tr>
          <th width="15%">Reference No.</th>
          <th width="12%">Order Amount</th>
          <th width="12%">Payments Made</th>
          <th width="12%">Unpaid Balance</th>
          <th width="10%">Date</th>
          <th width="10%">Due Date</th>
          <th width="10%">Delivered</th>
          <th width="19%">Remarks</th>
        </tr>
      </thead>
      <tbody>
        ${breakdowns
          .map(
            (breakdown) => `
          <tr>
            <td class="text-bold">${breakdown?.order_reference_no || "N/A"}</td>
            <td class="text-right">${breakdown?.order_total_amount || "N/A"}</td>
            <td class="text-right">${breakdown?.payments_total || "N/A"}</td>
            <td class="text-right">${breakdown?.unpaid_balance || "N/A"}</td>
            <td>${breakdown?.date || "N/A"}</td>
            <td>${breakdown?.due_date || "N/A"}</td>
            <td>${breakdown?.date_delivered || "N/A"}</td>
            <td>${breakdown?.remarks || "N/A"}</td>
          </tr>
          ${renderOrderDetails(breakdown?.order_form_details)}
        `,
          )
          .join("")}
      </tbody>
    </table>
  `;
};

const renderOrderDetails = (details) => {
  if (!details || !Array.isArray(details)) return "";

  return `
    <tr>
      <td colspan="8">
        <table class="order-details-table">
          <thead>
            <tr>
              <th width="70%">Product Name</th>
              <th width="30%">Quantity</th>
            </tr>
          </thead>
          <tbody>
            ${details
              .map(
                (detail) => `
              <tr>
                <td>${detail?.product?.menu || "N/A"}</td>
                <td class="text-right">${detail?.quantity || "N/A"}</td>
              </tr>
            `,
              )
              .join("")}
          </tbody>
        </table>
      </td>
    </tr>
  `;
};
module.exports = { createStatementPDF, createStatementMultiplePDF };
