import type { BusinessProfile } from './site-settings.helper';
import { buildDocumentShareEmailText, buildDocumentShareSms } from './notification-messages.helper';

function escapeHtml(value: unknown) {
  return String(value ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

function formatMoney(amount: number) {
  return `GHS ${Number(amount || 0).toLocaleString('en-GH', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

function formatDateLabel(date?: string) {
  if (!date) return '';
  if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
    const parsed = new Date(`${date}T12:00:00`);
    if (Number.isNaN(parsed.getTime())) return date;
    return parsed.toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
  }
  return date;
}

function formatIssuedDate(value?: unknown) {
  const today = () =>
    new Date().toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });

  if (!value) return today();

  const str = String(value);
  if (/^\d{4}-\d{2}-\d{2}$/.test(str)) {
    return formatDateLabel(str);
  }

  if (str.includes('T')) {
    const parsed = new Date(str);
    if (!Number.isNaN(parsed.getTime())) {
      return parsed.toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
    }
  }

  return formatDateLabel(str) || today();
}

function paymentMethodLabel(method?: string) {
  const map: Record<string, string> = {
    CASH: 'Cash',
    LINK: 'Paystack Link',
    CARD: 'Card',
    NONE: 'Not specified',
  };
  return map[method || ''] || method || 'Not specified';
}

function paymentStatusLabel(status?: string) {
  return String(status || 'UNPAID').replace(/_/g, ' ');
}

function buildLineItemRows(appointment: Record<string, unknown>, amountDue: number, amountPaid: number) {
  const lineItems = Array.isArray(appointment.lineItems) ? appointment.lineItems : [];
  if (lineItems.length) {
    return lineItems
      .map((item: Record<string, unknown>) => {
        const qty = Number(item.quantity || 1);
        const subtotal = Number(item.subtotal ?? (Number(item.unitPrice || 0) * qty));
        const typeLabel = item.type === 'PRODUCT' ? 'Product' : 'Service';
        return `<tr>
          <td>${escapeHtml(item.name)} <span style="color:#8a8175;font-size:12px;">(${typeLabel}${qty > 1 ? ` × ${qty}` : ''})</span></td>
          <td>${escapeHtml(String(appointment.date || ''))} · ${escapeHtml(String(appointment.time || ''))}</td>
          <td>${formatMoney(subtotal)}</td>
        </tr>`;
      })
      .join('');
  }

  return `<tr>
    <td>${escapeHtml(appointment.service)}</td>
    <td>${escapeHtml(String(appointment.date || ''))} · ${escapeHtml(String(appointment.time || ''))}</td>
    <td>${formatMoney(amountDue || amountPaid)}</td>
  </tr>`;
}

function buildServiceSummaryText(appointment: Record<string, unknown>) {
  const lineItems = Array.isArray(appointment.lineItems) ? appointment.lineItems : [];
  if (lineItems.length) {
    return lineItems.map((item: Record<string, unknown>) => String(item.name || '')).join(', ');
  }
  return String(appointment.service || '');
}

export function buildDocumentHtml(
  type: 'invoice' | 'receipt',
  appointment: Record<string, unknown>,
  business: BusinessProfile
) {
  const serviceSummary = buildServiceSummaryText(appointment);
  const number = type === 'invoice' ? appointment.invoiceNumber : appointment.receiptNumber;
  const title = type === 'invoice' ? 'Invoice' : 'Receipt';
  const issuedAt = formatIssuedDate(appointment.updatedAt || appointment.createdAt);
  const appointmentDate = formatDateLabel(String(appointment.date || ''));
  const amountDue = Number(appointment.amountDue || 0);
  const amountPaid = Number(appointment.amountPaid || 0);
  const amountRefunded = Number(appointment.amountRefunded || 0);
  const balance = Math.max(amountDue - amountPaid, 0);
  const isReceipt = type === 'receipt';

  const summaryRows = isReceipt
    ? `
      <tr><td>Amount paid</td><td>${formatMoney(amountPaid)}</td></tr>
      ${amountRefunded ? `<tr><td>Amount refunded</td><td>${formatMoney(amountRefunded)}</td></tr>` : ''}
      <tr class="total"><td>Payment method</td><td>${escapeHtml(paymentMethodLabel(String(appointment.paymentMethod || '')))}</td></tr>
    `
    : `
      <tr><td>Subtotal</td><td>${formatMoney(amountDue)}</td></tr>
      <tr><td>Amount paid</td><td>${formatMoney(amountPaid)}</td></tr>
      ${amountRefunded ? `<tr><td>Refunded</td><td>${formatMoney(amountRefunded)}</td></tr>` : ''}
      <tr class="total"><td>Balance due</td><td>${formatMoney(balance)}</td></tr>
    `;

  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>${escapeHtml(title)} ${escapeHtml(number)} — ${business.name}</title>
  <style>
    * { box-sizing: border-box; }
    body {
      margin: 0;
      padding: 48px 40px;
      font-family: "Helvetica Neue", Arial, sans-serif;
      color: #1a1a1a;
      background: #faf9f7;
      line-height: 1.5;
    }
    .page {
      max-width: 760px;
      margin: 0 auto;
      background: #fff;
      border: 1px solid #ece7df;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 18px 50px rgba(26, 26, 26, 0.08);
    }
    .header {
      display: flex;
      justify-content: space-between;
      gap: 24px;
      padding: 32px 36px 24px;
      border-bottom: 1px solid #f0ebe3;
      background: linear-gradient(135deg, #fff 0%, #faf6ef 100%);
    }
    .brand h1 {
      margin: 0;
      font-family: Georgia, "Times New Roman", serif;
      font-size: 28px;
      font-weight: 500;
      color: #b8860b;
      letter-spacing: 0.02em;
    }
    .brand p {
      margin: 6px 0 0;
      font-size: 12px;
      letter-spacing: 0.18em;
      text-transform: uppercase;
      color: #8a8175;
    }
    .doc-meta {
      text-align: right;
    }
    .badge {
      display: inline-block;
      padding: 6px 12px;
      border-radius: 999px;
      background: #1a1a1a;
      color: #fff;
      font-size: 11px;
      letter-spacing: 0.16em;
      text-transform: uppercase;
    }
    .doc-meta h2 {
      margin: 12px 0 4px;
      font-size: 22px;
      font-weight: 600;
    }
    .doc-meta p {
      margin: 0;
      font-size: 13px;
      color: #666;
    }
    .content { padding: 28px 36px 36px; }
    .grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
      margin-bottom: 28px;
    }
    .panel {
      padding: 18px 20px;
      border: 1px solid #eee7dc;
      border-radius: 10px;
      background: #fcfaf7;
    }
    .panel h3 {
      margin: 0 0 10px;
      font-size: 11px;
      letter-spacing: 0.14em;
      text-transform: uppercase;
      color: #8a8175;
    }
    .panel p {
      margin: 0 0 4px;
      font-size: 14px;
    }
    .panel .muted { color: #666; font-size: 13px; }
    table.items {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 24px;
    }
    table.items th,
    table.items td {
      padding: 14px 12px;
      border-bottom: 1px solid #eee7dc;
      text-align: left;
      font-size: 14px;
    }
    table.items th {
      font-size: 11px;
      letter-spacing: 0.12em;
      text-transform: uppercase;
      color: #8a8175;
      background: #fcfaf7;
    }
    table.items td:last-child,
    table.items th:last-child { text-align: right; }
    table.summary {
      width: 100%;
      max-width: 320px;
      margin-left: auto;
      border-collapse: collapse;
    }
    table.summary td {
      padding: 10px 0;
      border-bottom: 1px solid #f0ebe3;
      font-size: 14px;
    }
    table.summary td:last-child {
      text-align: right;
      font-weight: 600;
    }
    table.summary tr.total td {
      border-bottom: none;
      padding-top: 14px;
      font-size: 16px;
      color: #b8860b;
    }
    .status {
      display: inline-block;
      margin-top: 18px;
      padding: 8px 12px;
      border-radius: 8px;
      background: #f5f0e8;
      font-size: 12px;
      letter-spacing: 0.08em;
      text-transform: uppercase;
      color: #5c5348;
    }
    .footer {
      padding: 22px 36px 28px;
      border-top: 1px solid #f0ebe3;
      background: #fcfaf7;
      font-size: 12px;
      color: #666;
    }
    .footer strong { color: #1a1a1a; }
    @media print {
      body { background: #fff; padding: 0; }
      .page { box-shadow: none; border: none; border-radius: 0; }
    }
  </style>
</head>
<body>
  <div class="page">
    <div class="header">
      <div class="brand">
        <h1>${business.name}</h1>
        <p>${business.tagline}</p>
      </div>
      <div class="doc-meta">
        <span class="badge">${title}</span>
        <h2>${escapeHtml(number)}</h2>
        <p>Issued ${issuedAt}</p>
      </div>
    </div>

    <div class="content">
      <div class="grid">
        <div class="panel">
          <h3>Bill to</h3>
          <p><strong>${escapeHtml(appointment.fullName)}</strong></p>
          <p class="muted">${escapeHtml(appointment.phone)}</p>
          ${appointment.email ? `<p class="muted">${escapeHtml(appointment.email)}</p>` : ''}
        </div>
        <div class="panel">
          <h3>${isReceipt ? 'Payment details' : 'Appointment details'}</h3>
          <p><strong>${escapeHtml(serviceSummary)}</strong></p>
          <p class="muted">${appointmentDate}</p>
          <p class="muted">${escapeHtml(appointment.time)}</p>
        </div>
      </div>

      <table class="items">
        <thead>
          <tr>
            <th>Description</th>
            <th>Date</th>
            <th>Amount</th>
          </tr>
        </thead>
        <tbody>
          ${buildLineItemRows(appointment, amountDue, amountPaid)}
        </tbody>
      </table>

      <table class="summary">
        ${summaryRows}
      </table>

      ${isReceipt ? `<div class="status">Payment status: ${escapeHtml(paymentStatusLabel(String(appointment.paymentStatus || '')))}</div>` : ''}
    </div>

    <div class="footer">
      <p><strong>${business.name}</strong> · ${business.location}</p>
      <p>${business.phone} · ${business.email} · ${business.website}</p>
      <p style="margin-top: 12px;">Thank you for choosing ${business.name}. We look forward to seeing you again.</p>
    </div>
  </div>
</body>
</html>`;
}

export function buildDocumentShareText(
  type: 'invoice' | 'receipt',
  appointment: Record<string, unknown>,
  business: BusinessProfile,
  paymentLink?: { url?: string | null; amount?: number; status?: string } | null
) {
  return buildDocumentShareEmailText(type, { appointment, business, paymentLink });
}

export { buildDocumentShareSms, buildDocumentShareEmailText };
