const numberToWords = (num: number): string => {
  if (num === 0) return "Zero";

  const ones = [
    "",
    "One",
    "Two",
    "Three",
    "Four",
    "Five",
    "Six",
    "Seven",
    "Eight",
    "Nine",
  ];
  const teens = [
    "Ten",
    "Eleven",
    "Twelve",
    "Thirteen",
    "Fourteen",
    "Fifteen",
    "Sixteen",
    "Seventeen",
    "Eighteen",
    "Nineteen",
  ];
  const tens = [
    "",
    "",
    "Twenty",
    "Thirty",
    "Forty",
    "Fifty",
    "Sixty",
    "Seventy",
    "Eighty",
    "Ninety",
  ];

  const convertLessThanThousand = (n: number): string => {
    if (n === 0) return "";
    if (n < 10) return ones[n];
    if (n < 20) return teens[n - 10];
    if (n < 100)
      return (
        tens[Math.floor(n / 10)] + (n % 10 !== 0 ? " " + ones[n % 10] : "")
      );
    return (
      ones[Math.floor(n / 100)] +
      " Hundred" +
      (n % 100 !== 0 ? " " + convertLessThanThousand(n % 100) : "")
    );
  };

  let intPart = Math.floor(num);
  const decPart = Math.round((num - intPart) * 100);
  let result = "";

  if (intPart >= 10000000) {
    result +=
      convertLessThanThousand(Math.floor(intPart / 10000000)) + " Crore ";
    intPart %= 10000000;
  }
  if (intPart >= 100000) {
    result += convertLessThanThousand(Math.floor(intPart / 100000)) + " Lakh ";
    intPart %= 100000;
  }
  if (intPart >= 1000) {
    result +=
      convertLessThanThousand(Math.floor(intPart / 1000)) + " Thousand ";
    intPart %= 1000;
  }
  if (intPart > 0) {
    result += convertLessThanThousand(intPart);
  }

  result = result.trim() + " Rupees";
  if (decPart > 0) {
    result += " and " + convertLessThanThousand(decPart) + " Paise";
  }

  return result + " Only";
};

const formatDateTime = (dateString: string): string => {
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return "N/A";

    const day = String(date.getDate()).padStart(2, "0");
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const year = date.getFullYear();
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    return `${day}-${month}-${year} ${hours}:${minutes}`;
  } catch (error) {
    return "N/A";
  }
};

const flattenInvoiceData = (data: any): any[] => {
  console.log(data, "datadata");

  if (!data) return [];

  if (Array.isArray(data)) {
    if (data.length === 0) return [];

    // Flatten nested arrays
    const flattened = data.flat(2);

    // Return all valid invoice objects
    return flattened.filter(
      (item) => item && typeof item === "object" && item._id
    );
  }

  // Single object
  return [data];
};

const invoiceHTML = (invoiceData: any): string => {
  try {
    console.log(JSON.stringify(invoiceData), "invoiceData");
    const data = invoiceData.data[0];

    const invoices = flattenInvoiceData(data);
    console.log(`Processing::: ${invoices.length} invoice(s)`);
    console.log(invoices, "invoices");

    if (invoices.length === 0) {
      return '<html><body style="padding:20px;"><p>No valid invoice data available</p></body></html>';
    }

    // Take the first invoice for main data
    console.log(data, "data");

    const patient = invoiceData.data[0].patient_details || {};
    const patientName = patient.patient_name || "N/A";
    const patientId = patient.id || "N/A";
    const aayushId = patient.aayush_unique_id || "N/A";
    const age = patient.age || "N/A";
    const gender = patient.gender || "N/A";
    const mobile = patient.mobileno || "N/A";
    const address = patient.address || "N/A";
    const bloodGroup = patient.blood_group || "N/A";

    const hospitalName =
      invoiceData.data[0].hospital_details.hospital_name || "Plenome";
    const hospitalAddress =
      invoiceData.data[0].hospital_details.address ||
      "Healthcare Technology Innovation Centre (HTIC), 5th Floor, Block C, IITM Research Park, Kangam Road, Taramani, Chennai, Tamil Nadu - 600113";
    const hospitalPhone =
      invoiceData.data[0].hospital_details.contact_no || "+91 XXXXX XXXXX";
    const hospitalWebsite =
      invoiceData.data[0].hospital_details.website ||
      "https://www.cityhospital.com";

    const logoBase64 = invoiceData.data[0].hospital_details.logo_base64;
    const logoHTML = logoBase64
      ? `<img 
        src="data:image/png;base64,${logoBase64}" 
        class="hospital-logo"
        alt="Hospital Logo"
     />`
      : `<div class="logo">P</div>`;

    const invoiceNumber =
      data.hos_transaction_id || data.plenome_transaction_id || "N/A";
    const paymentStatus =
      data.payment_status === "success" ? "success" : "Unpaid";
    const paymentMethod =
      data.payment_mode === "aayush_coins"
        ? "Aayush Coins"
        : data.payment_mode === "cash"
          ? "cash"
          : data.payment_mode || "N/A";
    const invoiceDate = formatDateTime(
      data.created_at || new Date().toISOString()
    );

    const primaryDoctor = data.primary_cons_doctor
      ? `${data.primary_cons_doctor.name || ""} ${data.primary_cons_doctor.surname || ""}`.trim() +
        (data.primary_cons_doctor.employee_id
          ? ` (MBBS No: ${data.primary_cons_doctor.employee_id})`
          : "")
      : "N/A";

    const lastDoctor = data.last_cons_doctor
      ? `${data.last_cons_doctor.name || ""} ${data.last_cons_doctor.surname || ""}`.trim() +
        (data.last_cons_doctor.employee_id
          ? ` (MBBS No: ${data.last_cons_doctor.employee_id})`
          : "")
      : "N/A";

    // Check if we have multiple invoices
    const hasMultipleInvoices = invoices.length > 1;

    // Collect all items from all invoices
    let allItems: any[] = [];
    let globalItemNumber = 1;

    invoices.forEach((invoice, invoiceIndex) => {
      const transactions = Array.isArray(invoice.transaction_details)
        ? invoice.transaction_details
        : [];

      transactions.forEach((txn: any) => {
        const rate = parseFloat(txn.standard_charge || "0") || 0;
        const qty = parseInt(txn.qty || "1") || 1;
        const discountAmount = parseFloat(txn.discount_amount || "0") || 0;
        const taxAmount = parseFloat(txn.total_tax_amount || "0") || 0;
        const subtotal =
          parseFloat(txn.overall_subtotal_amount || "0") || rate * qty;
        const total = parseFloat(txn.total_billed_amount || "0") || 0;

        allItems.push({
          number: globalItemNumber++,
          invoiceIndex: invoiceIndex + 1,
          name: txn.module || txn.charge_type || "Service",
          caseId: txn.case_id || "N/A",
          provider: txn.name
            ? `${txn.name} ${txn.surname || ""}`.trim()
            : "N/A",
          date: formatDateTime(txn.billed_date || ""),
          departmentId: txn.department_id || txn.appointment_id || "N/A",
          qty,
          rate,
          discount: discountAmount,
          subtotal,
          taxAmount,
          total,
        });
      });
    });

    // Calculate totals from all invoices
    let subTotal = 0;
    let totalDiscount = 0;
    let totalTax = 0;
    let totalAmount = 0;
    let total = 0;

    invoices.forEach((invoice) => {
      const transactions = Array.isArray(invoice.transaction_details)
        ? invoice.transaction_details
        : [];
      subTotal += transactions.reduce(
        (sum: number, txn: any) =>
          sum + (parseFloat(txn.overall_subtotal_amount || "0") || 0),
        0
      );
      totalDiscount += transactions.reduce(
        (sum: number, txn: any) =>
          sum + (parseFloat(txn.discount_amount || "0") || 0),
        0
      );
      total += transactions.reduce(
        (sum: number, txn: any) =>
          sum + (parseFloat(txn.discount_amount || "0") || 0),
        0
      );
      totalTax += transactions.reduce(
        (sum: number, txn: any) =>
          sum + (parseFloat(txn.total_tax_amount || "0") || 0),
        0
      );
      totalAmount += parseFloat(invoice.amount_paid || "0") || 0;
    });

    const amountInWords = numberToWords(totalAmount);

    // const qrLink =
    //   Platform.OS === "android"
    //     ? "https://play.google.com/store/apps/details?id=com.plenome.aayush"
    //     : "https://apps.apple.com/in/app/aayush/id6479345356";
    const qrLink =
      "https://play.google.com/store/apps/details?id=com.plenome.aayush";

    return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Invoice - ${invoiceNumber}</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }

body {
  font-family: Arial, Helvetica, sans-serif;
  background: #fff;
  color: #222;
  font-size: 11px;
}

.invoice-container {
  max-width: 1000px;
  margin: auto;
  padding: 18px;
}

/* ===== HEADER LAYOUT (FIGMA MATCH) ===== */
.header {
  display: grid;
  grid-template-columns: 1fr 260px;
  align-items: center;
  border-bottom: 2px solid #1f4fd8;
  padding-bottom: 12px;
  margin-bottom: 16px;
}

/* LEFT */
.header-left {
  display: flex;
  align-items: flex-start;
}

.logo-row {
  display: flex;
  gap: 12px;
}

.hospital-logo,
.logo {
  width: 46px;
  height: 46px;
}

.hospital-block {
  display: flex;
  flex-direction: column;
}

.hospital-name {
  font-size: 16px;
  font-weight: 700;
  color: #1f4fd8;
  line-height: 46px;
  height: 46px;
}

.hospital-address {
  font-size: 11px;
  color: #555;
  line-height: 1.35;
  max-width: 420px;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* RIGHT */
.header-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  text-align: right;
  gap: 6px;
}

.invoice-title {
  font-size: 16px;
  font-weight: 700;
}

.barcode-svg {
  width: 180px;
  height: 42px;
}

.barcode-meta {
  font-size: 11px;
  line-height: 1.4;
}

.patient-id {
  font-weight: 700;
}

.aayush-id {
  font-size: 10px;
  color: #555;
  word-break: break-all;
}


/* ===== INFO GRID ===== */
.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  background: #f5f7fb;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 18px;
}

.info-section h3 {
  font-size: 13px;
  color: #1f4fd8;
  margin-bottom: 10px;
}

.info-row {
  display: flex;
  margin-bottom: 6px;
}

.info-label {
  width: 140px;
  color: #555;
}

.info-value {
  font-weight: bold;
}

/* ===== TABLE ===== */
.particulars-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 10px;
}

.items-table {
  width: 100%;
  border-collapse: collapse;
}

.items-table thead {
  background: #1f4fd8;
  color: #fff;
}

.items-table th,
.items-table td {
  padding: 8px;
  border-bottom: 1px solid #ddd;
  font-size: 11px;
}

.text-center { text-align: center; }
.text-right { text-align: right; }

.item-name {
  font-weight: bold;
}

.item-details {
  font-size: 10px;
  color: #555;
}

/* ===== SUMMARY ===== */
.summary-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.summary-box {
  width: 360px;
  background: #f5f7fb;
  padding: 14px;
  border-radius: 6px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.summary-total {
  border-top: 2px solid #222;
  padding-top: 8px;
  font-weight: bold;
}

/* ===== AMOUNT IN WORDS ===== */
.amount-words {
  text-align: center;
  margin: 18px 0;
  padding: 12px;
  background: #f5f7fb;
  border-radius: 6px;
}

.amount-words strong {
  display: block;
  margin-top: 4px;
  font-size: 13px;
  color: #1f4fd8;
}

/* ===== FOOTER ===== */
.footer {
  display: flex;
  justify-content: space-between;
  background: #f5f7fb;
  padding: 14px;
  border-radius: 6px;
}

.contact-info h4 {
  color: #1f4fd8;
  margin-bottom: 6px;
}

.qr-box {
  width: 96px;
  height: 96px;
  border: 1px solid #ccc;
}

.qr-text {
  font-size: 10px;
  margin-top: 4px;
  text-align: center;
}

/* ===== WATERMARK ===== */
.watermark {
  text-align: center;
  margin-top: 18px;
  font-size: 10px;
  color: #888;
}

/* ===== PRINT ===== */
@media print {
  .header,
  .info-grid,
  .footer {
    break-inside: avoid;
    page-break-inside: avoid;
  }

  thead {
    display: table-header-group;
  }
}

@media print {
  body { margin: 0; }
  .invoice-container { padding: 0; }
}


/* Responsive adjustments */
@media screen and (max-width: 768px) {
  body { padding: 10px; }
  
  .header { 
    flex-direction: column;
  }
  
  .invoice-title-section {
    text-align: left;
    width: 100%;
  }
  
  .barcode-section {
    align-items: flex-start;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .summary-section {
    justify-content: stretch;
  }
  
  .summary-box {
    width: 100%;
    min-width: unset;
  }
  
  .footer {
    flex-direction: column;
    text-align: center;
  }
  
  .contact-info {
    width: 100%;
  }

  .header,
.info-grid,
.particulars-section,
.summary-section,
.amount-words,
.footer {
  page-break-inside: avoid;
  break-inside: avoid;
}

}

@media print {
  body { padding: 0; }
  .invoice-container { max-width: 100%; }
  .table-wrapper { overflow-x: visible; }
}
  @page {
  size: A4;
  margin: 10mm;
}
</style>


</head>
<body>

<div class="invoice-container">
  
  <div class="header">
    <div class="header-left">
      <div class="logo-row">
        ${logoHTML}
        <div class="hospital-block">
          <div class="hospital-name">${hospitalName}</div>
          <div class="hospital-address">${hospitalAddress}</div>
        </div>
      </div>
    </div>

    <div class="header-right">
      <div class="invoice-title">Invoice</div>
      <svg id="barcode" class="barcode-svg"></svg>
      <div class="barcode-meta">
        <div class="patient-id">Patient ID : ${patientId}</div>
        <div class="aayush-id">Aayush ID : ${aayushId}</div>
      </div>
    </div>
  </div>



  <div class="info-grid">
    <div class="info-section">
      <h3>Patient Information</h3>
      <div class="info-row">
        <span class="info-label">Name:</span>
        <span class="info-value">${patientName}</span>
      </div>
      <div class="info-row">
        <span class="info-label">Patient ID:</span>
        <span class="info-value">${patientId}</span>
      </div>
      <div class="info-row">
        <span class="info-label">Blood Group:</span>
        <span class="info-value">${bloodGroup}</span>
      </div>
      <div class="info-row">
        <span class="info-label">Age:</span>
        <span class="info-value">${age} Years</span>
      </div>
      <div class="info-row">
        <span class="info-label">Gender:</span>
        <span class="info-value">${gender}</span>
      </div>
      <div class="info-row">
        <span class="info-label">UHId Number:</span>
        <span class="info-value">${aayushId}</span>
      </div>
      <div class="info-row">
        <span class="info-label">Mobile:</span>
        <span class="info-value">${mobile}</span>
      </div>
      <div class="info-row">
        <span class="info-label">Address:</span>
        <span class="info-value">${address}</span>
      </div>
    </div>
    
    <div class="info-section">
      <h3>Invoice Details</h3>
      <div class="info-row">
        <span class="info-label">Invoice Number:</span>
        <span class="info-value">${invoiceNumber}</span>
      </div>
      <div class="info-row">
        <span class="info-label">Payment Status:</span>
        <span class="info-value ${paymentStatus === "success" ? "status-success" : ""}">${paymentStatus}</span>
      </div>
      <div class="info-row">
        <span class="info-label">Payment Method:</span>
        <span class="info-value">${paymentMethod}</span>
      </div>
      <div class="info-row">
        <span class="info-label">Date & Time:</span>
        <span class="info-value">${invoiceDate}</span>
      </div>
      <div class="info-row">
        <span class="info-label">Primary Consultation Doctor:</span>
        <span class="info-value">${primaryDoctor}</span>
      </div>
      <div class="info-row">
        <span class="info-label">Last Consultation Doctor:</span>
        <span class="info-value">${lastDoctor}</span>
      </div>
    </div>
  </div>

  <div class="particulars-section">
    <h2 class="particulars-title">Particulars</h2>
    <div class="table-wrapper">
      <table class="items-table">
        <thead>
          <tr>
            <th style="width: 30%;">Name</th>
            <th class="text-center" style="width: 12%;">Department Id</th>
            <th class="text-center" style="width: 8%;">Qty</th>
            <th class="text-right" style="width: 10%;">Rate</th>
            <th class="text-right" style="width: 10%;">Discount</th>
            <th class="text-right" style="width: 10%;">Sub Total</th>
            <th class="text-right" style="width: 10%;">Tax Amt</th>
            <th class="text-right" style="width: 10%;">Amount (Rs)</th>
          </tr>
        </thead>
        <tbody>
          ${allItems
            .map(
              (item: any) => `
          <tr>
            <td>
              <div class="item-name">${item.number}. ${hasMultipleInvoices ? `APPT ${item.invoiceIndex}` : item.name}</div>
              <div class="item-details">
                ${hasMultipleInvoices ? item.name + "<br>" : ""}
                Case: ${item.caseId} | Date: ${item.date}
              </div>
            </td>
            <td class="text-center">${item.departmentId}</td>
            <td class="text-center">${item.qty}</td>
            <td class="text-right">${item.rate.toFixed(2)}</td>
            <td class="text-right">${item.discount.toFixed(2)}</td>
            <td class="text-right">${item.subtotal.toFixed(2)}</td>
            <td class="text-right">${item.taxAmount.toFixed(2)}</td>
            <td class="text-right" style="font-weight: 700;">${item.total.toFixed(2)}</td>
          </tr>
          `
            )
            .join("")}
        </tbody>
      </table>
    </div>
  </div>

  ${
    !hasMultipleInvoices
      ? `
  <div class="summary-section">
    <div class="summary-box">
     <div class="summary-row">
        <span class="summary-label">Total</span>
        <span class="summary-value">${Number(totalDiscount.toFixed(2)) + Number(subTotal.toFixed(2))}</span>
      </div>
     <div class="summary-row">
        <span class="summary-label">Total Discount</span>
        <span class="summary-value">${totalDiscount.toFixed(2)}</span>
      </div>
      <div class="summary-row">
        <span class="summary-label">Sub Total</span>
        <span class="summary-value">${subTotal.toFixed(2)}</span>
      </div>
     
      <div class="summary-row">
        <span class="summary-label">Total Tax</span>
        <span class="summary-value">${totalTax.toFixed(2)}</span>
      </div>
      <div class="summary-row summary-total">
        <span class="summary-label">Amount Payable</span>
        <span class="summary-value">${totalAmount.toFixed(2)}</span>
      </div>
    </div>
  </div>
  `
      : ""
  }

  <div class="amount-words">
    Amount Chargeable (in Words):
    <strong>${amountInWords}</strong>
  </div>

  <div class="footer">
    <div class="contact-info">
      <h4>Hospital Contact</h4>
      <p><strong>Phone:</strong> ${hospitalPhone}</p>
      <p><strong>Website:</strong> ${hospitalWebsite}</p>
    </div>
    <div class="qr-section">
      <div class="qr-box" id="qrBox"></div>
      <p class="qr-text">Scan to Download<br>Aayush Mobile App</p>
    </div>
  </div>

  <div class="watermark">
    This invoice is computer generated
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jsbarcode/3.11.6/JsBarcode.all.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script>
window.addEventListener('load', function() {
  setTimeout(function() {
    try {
      const barcodeEl = document.getElementById("barcode");
      if (barcodeEl && typeof JsBarcode !== 'undefined') {
        JsBarcode(barcodeEl, "PT${patientId}", {
          format: "CODE128",
          lineColor: "#000",
          width: 2,
          height: 40,
          displayValue: false,
          margin: 5
        });
      }
    } catch (e) {
      console.error("Barcode error:", e);
    }

    try {
      const qrBox = document.getElementById("qrBox");
      if (qrBox && typeof QRCode !== 'undefined') {
        qrBox.innerHTML = '';
        new QRCode(qrBox, {
          text: "${qrLink}",
          width: 96,
          height: 96,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.M
        });
      }
    } catch (e) {
      console.error("QR error:", e);
    }
  }, 200);
});
</script>
</body>
</html>`;
  } catch (error) {
    console.error("Error generating invoice:", error);
    return `<html><body style="padding:20px;"><p style="color:red;">Error: ${error instanceof Error ? error.message : "Unknown error"}</p></body></html>`;
  }
};

export default invoiceHTML;
