export const generateInvoiceHtml = (payload: any) => {
  const {
    invoiceNumber,
    status,
    invoiceDate,
    dueDate,
    period,
    serviceTo,
    invoiceTo,
    summary,
    trips,
    notes,
    isDirectCustomer, // Add this flag to payload if not present
  } = payload

  const logoUrl = `${process.env.BACK_URL}/static-images/nuskin-logo.png`
  const renderInfoField = (label: string, value: any) => {
    if (value === null || value === undefined || value === "") {
      return ""
    }
    return `<p>${label}: ${value}</p>`
  }
  const renderStatus = (value: any) => {
    if (!value) return ""

    const status = value.toLowerCase() === "unpaid" ? "due" : value

    const formattedStatus = status
      .replaceAll("_", " ")
      .replace(/\b\w/g, (c) => c.toUpperCase())

    return `<p>Status : <span class="status-label">${formattedStatus}</span></p>`
  }
  const formatCurrency = (value: any) => {
    if (value === null || value === undefined || value === "") {
      return ""
    }
    if (typeof value === "number") {
      return value.toFixed(2)
    }
    const numericValue = Number(value)
    if (!Number.isNaN(numericValue)) {
      return numericValue.toFixed(2)
    }
    return value
  }
  const renderSummaryRow = (label: string, value: any) => {
    if (value === null || value === undefined || value === "") {
      return ""
    }
    const formattedValue = formatCurrency(value)
    if (formattedValue === "") {
      return ""
    }
    return `
                <tr >
                    <td style="text-align:left;padding:3px 12px;color:#0e4c92;font-size:15px;">${label}</td>
                    <td style="text-align:right;padding:3px 12px;color:#0e4c92;font-size:15px;">$${formattedValue}</td>
                </tr>`
  }
  const renderTotalRow = (label: string, value: any) => {
    if (value === null || value === undefined || value === "") {
      return ""
    }
    const formattedValue = formatCurrency(value)
    if (formattedValue === "") {
      return ""
    }
    return `
                <tr style="font-weight:bold;">
                    <td style="text-align:left;padding:3px 12px;color:#0e4c92;font-size:15px;font-weight:bold;">${label}</td>
                    <td style="text-align:right;padding:3px 12px;color:#0e4c92;font-size:15px;font-weight:bold;">$${formattedValue}</td>
                </tr>`
  }
  const renderPeriod = (periodValue: any) => {
    const start = periodValue?.start
    const end = periodValue?.end
    if (!start && !end) {
      return ""
    }
    const formatted = [start, end].filter(Boolean).join(" - ")
    if (!formatted) {
      return ""
    }
    return `<p>Period: ${formatted}</p>`
  }
  const safeServiceTo = serviceTo ?? {}
  const safeInvoiceTo = invoiceTo ?? {}
  const safeSummary = summary ?? {}
  const safeTrips = Array.isArray(trips) ? trips : []
  // Check if customer is direct
  // Method 1: Use isDirectCustomer flag
  // Method 2: Check if invoiceTo is empty
  const isDirectCust =
    isDirectCustomer ||
    (!safeInvoiceTo.name &&
      !safeInvoiceTo.email &&
      !safeInvoiceTo.phoneNumber &&
      !safeInvoiceTo.address)
  // Conditional rendering of BILL TO box
  const renderBillToBox = () => {
    if (isDirectCust) {
      return "" // Don't render if direct customer
    }
    return `
            <div class="info-box">
                <div class="info-box-title">BILL TO</div>
                <div class="info-box-content">
                    ${renderInfoField("Name", safeInvoiceTo.name)}
                    ${renderInfoField("Email", safeInvoiceTo.email)}
                    ${renderInfoField("Phone Number", safeInvoiceTo.phoneNumber)}
                    ${renderInfoField("Address", safeInvoiceTo.address)}
                </div>
            </div>`
  }
  return `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>${invoiceNumber ? `${invoiceNumber}` : "Nuskin Elite Team Invoice"}</title>
 <style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap');
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Roboto', Arial, sans-serif;
    }
    body {
      color: #333;
      line-height: 1.4;
      padding: 20px;
      margin: 0;
    }
    .invoice-container {
      max-width: 800px;
      margin: 0 auto;
      padding-bottom: 40px;
      position: relative;
    }
.summary-list  {
display:flex !important; justify-content:space-between !important;}
    /* Header */
    .invoice-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
    }
    .company-info {
      flex: 1;
    }
    .company-name {
      color: #E42C2E;
      font-weight: 500;
      font-size: 14px;
      margin-bottom: 5px;
    }
    .company-details {
      font-size: 12px;
      line-height: 1.4;
      color: #0e4c92;
    }
    .company-logo {
      text-align: right;
    }
    .company-logo img {
      max-width: 200px;
      height: auto;
    }
    .info-boxes {
      display: flex;
      justify-content: space-between;
      gap: 15px;
      margin-bottom: 20px;
    }
    .info-box {
      flex: 1;
      border: 1.5px solid #0e4c92;
      border-radius: 10px;
      padding: 15px;
    }
    .info-box-title {
      color: #E42C2E;
      font-weight: bold;
      font-size: 14px;
      margin-bottom: 10px;
    }
    .info-box-content {
      font-size: 14px;
      line-height: 1.6;
      color: #0e4c92;
    }
    .invoice-table {
      width: 100%;
      border-collapse: collapse;
      border: 1px solid #0e4c92;
    }
    .invoice-table th {
      background-color: #E42C2E;
      color: white;
      text-align: center;
      padding: 10px;
      font-weight: 400;
      font-size: 13px;
    }
    .invoice-table td {
      padding: 10px;
      border-bottom: 1px solid #0e4c92;
      border-right: 1px solid #0e4c92;
      font-size: 12px;
      vertical-align: top;
    }
    .invoice-table td:first-child {
      border-left: 1px solid #0e4c92;
    }
    .invoice-table tr:nth-child(even) {
      background-color: #f2f2f2;
    }
    .blue-text {
      color: #0e4c92;
    }
  </style>
</head>
<body>
    <div class="invoice-container">
        <!-- Header -->
        <div class="invoice-header">
            <div class="company-info">
                <div class="company-name">NUSKIN ELITE TEAM, INC.</div>
                <div class="company-details">
                    6074 Troy St.<br>
                    Chicago, IL 60659<br>
                    (800) 21-5462<br>
                    Finance@nuskinteam.net
                </div>
            </div>
            <div class="company-logo">
                <div class="nuskin-logo">
                    <div class="logo-icon">
                        <img src="${logoUrl}" alt="Company Logo" width="250" height="250" />
                    </div>
                </div>
            </div>
        </div>
        <!-- Info Boxes -->
        <div class="info-boxes">
            <div class="info-box">
                <div class="info-box-title">INVOICE INFORMATION</div>
                <div class="info-box-content">
                    ${renderInfoField("Invoice Number", invoiceNumber)}
                    ${renderInfoField("Invoice Date", invoiceDate)}
                    ${renderInfoField("Due Date", dueDate)}
                    ${renderPeriod(period)}
                    ${renderStatus(status)}
                </div>
            </div>
            <div class="info-box">
                <div class="info-box-title">SERVICE TO</div>
                <div class="info-box-content">
                    ${renderInfoField("PRN", safeServiceTo.service_to_prn)}
                    ${renderInfoField("City", safeServiceTo.City)}
                    ${renderInfoField("Name", safeServiceTo.name)}
                    ${renderInfoField("Email", safeServiceTo.email)}
                    ${renderInfoField("Phone Number", safeServiceTo.phoneNumber)}
                    ${renderInfoField("Address", safeServiceTo.address)}
                </div>
            </div>
            ${renderBillToBox()}
        </div>
        <!-- Trips Table -->
        <table class="invoice-table">
            <thead>
                <tr>
                    <th class="line-column">Line</th>
                    <th class="date-column">Date</th>
                    <th class="description-column">Description</th>
                    <th class="qty-column">Qty</th>
                    <th class="uom-column">UOM</th>
                    <th class="rate-column">Rate</th>
                    <th class="amount-column">Amount</th>
                </tr>
            </thead>
            <tbody>
                ${safeTrips
                  .map((t: any, index: number) => {
                    const amount = formatCurrency(t?.amount)
                    return `
                <tr>
                    <td class="blue-text">${index + 1}</td>
                    <td class="blue-text">${t?.date || ""}</td>
                    <td class="blue-text description-column">
                        ${(() => {
                          let [pickupTime, dropoffTime] =
                            t?.time?.split(" - ") || []
                          if (pickupTime)
                            pickupTime = pickupTime
                              .split(" ")
                              .slice(1)
                              .join(" ")
                          if (dropoffTime)
                            dropoffTime = dropoffTime
                              .split(" ")
                              .slice(1)
                              .join(" ")
                          let sentence = ""
                          if (t?.pickup) {
                            sentence += `From ${t.pickup}`
                            if (!isDirectCust && pickupTime) {
                              sentence += ` at ${pickupTime}`
                            }
                          }
                          if (t?.dropoff) {
                            sentence += `, to ${t.dropoff}`
                            if (!isDirectCust && dropoffTime) {
                              sentence += ` at ${dropoffTime}`
                            }
                          }
                          if (t?.carUsed) sentence += `, ${t.carUsed}`
                          if (t?.service_type) sentence += `, ${t.service_type}`
                          if (!isDirectCust && t?.appointmentType) {
                            sentence += `, ${t.appointmentType}`
                          }
                          if (t?.addOnWithQuantityAndPrice?.length > 0) {
                            sentence += `, ${t.addOnWithQuantityAndPrice.join(", ")}`
                          }
                          return sentence
                        })()}
                    </td>
                    <td class="blue-text">1</td>
                    <td class="blue-text">${t?.charge_type ? `${t?.charge_type}` : ""}</td>
                    <td class="blue-text">${t?.base_price ? `${t?.base_price}` : ""}</td>
                    <td class="blue-text">${amount ? `${amount}` : ""}</td>
                </tr>
                `
                  })
                  .join("")}
            </tbody>
        </table>
        <!-- Summary Section -->
        <div style="display:flex;justify-content:flex-end;">
            <table style="width:300px;border:1.5px solid #0e4c92;border-collapse:collapse;">
                ${renderSummaryRow("Sub Total", safeSummary.subtotal)}
                ${renderSummaryRow("Tax", safeSummary.taxAmount)}
                ${renderSummaryRow("Discount", safeSummary.discountAmount)}
                ${renderTotalRow("Total", safeSummary.total)}
            </table>
        </div>
        <!-- Notes & Bank -->
        <div style="display:flex;gap:15px;margin-top:30px;margin-bottom:30px;flex-wrap:wrap;">
            ${
              notes
                ? `<div style="flex:1;min-width:200px;border:1.5px solid #0e4c92;border-radius:10px;padding:15px;">
                <div style="color:#dc2626;font-weight:bold;font-size:14px;margin-bottom:10px;">INVOICE NOTES</div>
                <div style="color:#0e4c92;font-size:12px;line-height:1.6;">
                    ${notes}
                </div>
            </div>`
                : ""
            }
            <div style="flex:1;min-width:200px;border:1.5px solid #0e4c92;border-radius:10px;padding:15px;">
                <div style="color:#dc2626;font-weight:bold;font-size:14px;margin-bottom:10px;">BANK ACCOUNT DETAILS
                </div>
                <div style="color:#0e4c92;font-size:12px;line-height:1.6;">
                    <p><strong>Account Name:</strong> Nuskin Elite Team</p>
                    <p><strong>Bank Name:</strong> JPMorgan Chase Bank</p>
                    <p><strong>Routing Number (ACH):</strong> 071000013</p>
                    <p><strong>Routing Number (Wire):</strong> 021000021</p>
                    <p><strong>Account Number:</strong> 587601306</p>
                    <p><strong>Account Type:</strong> Checking</p>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
  `
}
