/**
 * Invoice PDF preview renderer — invoice-pdf-customization.
 *
 * Renders a deterministic sample invoice as a self-contained HTML document that
 * can be posted to the shared HTML-to-PDF worker.
 */
import type { InvoicePdfTemplate } from '@zync/db/queries'

interface SampleLine {
  description: string
  project: string
  sku: string
  quantity: number
  unitPrice: number
  taxRate: number
  amount: number
}

const SAMPLE_LINES: SampleLine[] = [
  {
    description: 'Website Refresh',
    project: 'Marathon Launch',
    sku: 'SKU-001',
    quantity: 1,
    unitPrice: 2000,
    taxRate: 17,
    amount: 2000,
  },
  {
    description: 'Full-Stack Development',
    project: 'Marathon Launch',
    sku: 'SKU-002',
    quantity: 1,
    unitPrice: 8000,
    taxRate: 17,
    amount: 8000,
  },
]

const SAMPLE_SUBTOTAL = 10000
const SAMPLE_VAT = 1700
const SAMPLE_TOTAL = 11700

const UI_TOKENS_CSS = `:root {
  --bg: oklch(100% 0 0);
  --surface: oklch(96% 0.012 195);
  --surface-strong: oklch(92% 0.02 195);
  --accent: oklch(44% 0.12 195);
  --ink: oklch(12% 0.04 240);
  --ink-soft: oklch(22% 0.045 240);
  --ink-faint: oklch(43% 0.035 235);
  --ink-on-accent: oklch(100% 0 0);
  --line: oklch(90% 0.03 195);
}`

function esc(s: unknown): string {
  return String(s ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
}

function formatDate(dateStr: string, format: InvoicePdfTemplate['dateFormat']): string {
  const d = new Date(dateStr)
  const dd = String(d.getDate()).padStart(2, '0')
  const MM = String(d.getMonth() + 1).padStart(2, '0')
  const yyyy = d.getFullYear()
  const month = d.toLocaleString('en-US', { month: 'long' })
  const day = d.getDate()

  switch (format) {
    case 'dd.MM.yyyy':
      return `${dd}.${MM}.${yyyy}`
    case 'yyyy-MM-dd':
      return `${yyyy}-${MM}-${dd}`
    case 'MMMM d, yyyy':
      return `${month} ${day}, ${yyyy}`
  }
}

function formatILS(amount: number): string {
  return `₪${amount.toLocaleString('en-IL', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}

function buildGridColumns(template: InvoicePdfTemplate): string {
  const cols = ['minmax(18rem, 2.3fr)']
  if (template.showProject) cols.push('minmax(8rem, 1.2fr)')
  if (template.showSku) cols.push('minmax(7rem, 1fr)')
  cols.push('4.5rem', '7rem', '5.5rem', '7rem')
  return cols.join(' ')
}

function renderHeaderCell(label: string, alignEnd = false): string {
  return `<div role="columnheader"${alignEnd ? ' class="num"' : ''}>${label}</div>`
}

function renderLineCell(value: string, alignEnd = false): string {
  return `<div role="cell"${alignEnd ? ' class="num"' : ''}>${value}</div>`
}

export function renderInvoicePdfPreview(template: InvoicePdfTemplate): string {
  const issueDate = formatDate('2026-06-01', template.dateFormat)
  const dueDate = formatDate('2026-06-30', template.dateFormat)
  const usesAccent = template.layout !== 'minimal'
  const accentOverride = usesAccent && template.accentHex ? `--pdf-accent:${template.accentHex};` : ''
  const accent = usesAccent ? 'var(--pdf-accent, var(--accent))' : 'var(--ink)'
  const isModern = template.layout === 'modern'
  const isMinimal = template.layout === 'minimal'
  const tableColumns = buildGridColumns(template)
  const brandBlock = isMinimal
    ? `<div class="brand-meta">
            <h1>Invoice</h1>
            <p>Acme Corp Ltd.</p>
            <p>3 Barzel St, Tel Aviv</p>
          </div>`
    : `<div class="brand-block">
          <div class="logo-badge">LOGO</div>
          <div class="brand-meta">
            <h1>Invoice</h1>
            <p>Acme Corp Ltd.</p>
            <p>3 Barzel St, Tel Aviv</p>
          </div>
        </div>`

  const lineRows = SAMPLE_LINES.map((line) => {
    const cells = [
      renderLineCell(esc(line.description)),
      ...(template.showProject ? [renderLineCell(esc(line.project))] : []),
      ...(template.showSku ? [renderLineCell(esc(line.sku))] : []),
      renderLineCell(String(line.quantity), true),
      renderLineCell(formatILS(line.unitPrice), true),
      renderLineCell(`${line.taxRate}%`, true),
      renderLineCell(formatILS(line.amount), true),
    ]
    return `<div role="row" class="line-row">${cells.join('')}</div>`
  }).join('')

  const headerCells = [
    renderHeaderCell('Description'),
    ...(template.showProject ? [renderHeaderCell('Project')] : []),
    ...(template.showSku ? [renderHeaderCell('SKU')] : []),
    renderHeaderCell('Qty', true),
    renderHeaderCell('Unit Price', true),
    renderHeaderCell('Tax Rate', true),
    renderHeaderCell('Amount', true),
  ].join('')

  return `<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>Sample Invoice Preview</title>
<style>
  ${UI_TOKENS_CSS}
  ${accentOverride}
  * { box-sizing: border-box; }
  body {
    margin: 0;
    padding: 32px;
    font-family: 'Heebo', 'Arial', sans-serif;
    color: var(--ink);
    background: var(--bg);
  }
  .page {
    max-width: 820px;
    margin: 0 auto;
    border: 1px solid var(--line);
    border-radius: 18px;
    overflow: hidden;
    background: white;
  }
  .accent-band {
    height: ${isModern ? '14px' : '8px'};
    background: ${usesAccent ? accent : 'var(--line)'};
  }
  .body {
    padding: ${isMinimal ? '28px' : '32px'};
  }
  .hero {
    display: grid;
    grid-template-columns: ${isModern ? '1.1fr 0.9fr' : '0.9fr 1.1fr'};
    gap: 24px;
    align-items: start;
    margin-bottom: 28px;
  }
  .brand-block {
    display: flex;
    gap: 14px;
    align-items: center;
  }
  .logo-badge {
    width: 56px;
    height: 56px;
    border-radius: 16px;
    display: grid;
    place-items: center;
    background: ${usesAccent ? accent : 'var(--surface-strong)'};
    color: ${usesAccent ? 'var(--ink-on-accent)' : 'var(--ink)'};
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 0.08em;
  }
  .brand-meta h1 {
    margin: 0 0 4px;
    font-size: ${isMinimal ? '1.9rem' : '2.2rem'};
    color: ${accent};
  }
  .brand-meta p,
  .invoice-meta,
  .party p,
  .totals-label,
  .footer {
    color: var(--ink-faint);
  }
  .invoice-meta {
    text-align: ${isModern ? 'right' : 'left'};
    justify-self: ${isModern ? 'end' : 'start'};
    line-height: 1.7;
  }
  .parties {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-bottom: 28px;
  }
  .party {
    padding: 18px;
    border: 1px solid var(--line);
    border-radius: 14px;
    background: ${isMinimal ? 'transparent' : 'var(--surface)'};
  }
  .party h2 {
    margin: 0 0 8px;
    font-size: 0.8rem;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: ${accent};
  }
  .table {
    margin-bottom: 24px;
  }
  .table [role="row"] {
    display: grid;
    grid-template-columns: ${tableColumns};
  }
  .table [role="columnheader"] {
    padding: 12px 14px;
    font-size: 0.82rem;
    font-weight: 700;
    background: ${usesAccent ? accent : 'var(--surface-strong)'};
    color: ${usesAccent ? 'var(--ink-on-accent)' : 'var(--ink)'};
    border-bottom: 1px solid var(--line);
  }
  .table [role="cell"] {
    padding: 13px 14px;
    border-bottom: 1px solid var(--line);
  }
  .table .line-row:nth-child(even) [role="cell"] {
    background: var(--surface);
  }
  .num {
    text-align: right;
    font-variant-numeric: tabular-nums;
  }
  .totals {
    width: 320px;
    margin-left: auto;
    border-top: 2px solid ${accent};
    padding-top: 12px;
  }
  .totals-row {
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 16px;
    padding: 8px 0;
  }
  .totals-row strong {
    color: ${accent};
    font-size: 1.08rem;
  }
  .footer {
    margin-top: 32px;
    text-align: center;
    font-size: 0.78rem;
  }
  @media print {
    body { padding: 0; background: white; }
    .page { border: none; border-radius: 0; }
    @page { margin: 1.4cm; }
  }
</style>
</head>
<body>
  <div class="page">
    <div class="accent-band"></div>
    <div class="body">
      <div class="hero">
        ${brandBlock}
        <div class="invoice-meta">
          <div><strong>INV-0001</strong></div>
          <div>Issue date: ${issueDate}</div>
          <div>Due date: ${dueDate}</div>
        </div>
      </div>

      <div class="parties">
        <section class="party">
          <h2>From</h2>
          <p><strong>Acme Corp Ltd.</strong></p>
          <p>VAT 51-234567-8</p>
          <p>billing@acme.example</p>
        </section>
        <section class="party">
          <h2>Bill To</h2>
          <p><strong>Dana Cohen</strong></p>
          <p>Marathon Ventures</p>
          <p>dana@marathon.example</p>
        </section>
      </div>

      <div class="table" role="table" aria-label="Invoice line items">
        <div role="rowgroup">
          <div role="row">${headerCells}</div>
        </div>
        <div role="rowgroup">${lineRows}</div>
      </div>

      <div class="totals">
        <div class="totals-row"><span class="totals-label">Subtotal</span><span>${formatILS(SAMPLE_SUBTOTAL)}</span></div>
        <div class="totals-row"><span class="totals-label">VAT 17%</span><span>${formatILS(SAMPLE_VAT)}</span></div>
        <div class="totals-row"><strong>Total due</strong><strong>${formatILS(SAMPLE_TOTAL)}</strong></div>
      </div>

      <div class="footer">Thank you for your business.</div>
    </div>
  </div>
</body>
</html>`
}
