export type ReportPdfColumn = {
  key: string
  label: string
  align?: "start" | "end" | "center"
}

export type ReportPdfMetric = {
  label: string
  value: string
}

export type ReportPdfFilter = {
  label: string
  value: string
}

export type ReportPdfRow = Record<string, string>

export type ReportPdfLabels = {
  generated: string
  generatedBy: string
  filters: string
  summary: string
  results: string
  noData: string
  dashboard: string
  confidential: string
  rows: string
}

export type ReportPdfInput = {
  title: string
  subtitle: string
  reportCode: string
  language: string
  generatedAt: string
  generatedBy?: string | null
  filters: ReportPdfFilter[]
  metrics: ReportPdfMetric[]
  columns: ReportPdfColumn[]
  rows: ReportPdfRow[]
  labels: ReportPdfLabels
}

export function printReportPdf(input: ReportPdfInput, filename: string) {
  const html = buildReportHtml(input, filename)
  const printWindow = window.open("", "_blank", "width=1120,height=900")

  if (!printWindow) {
    const iframe = document.createElement("iframe")
    iframe.style.position = "fixed"
    iframe.style.right = "0"
    iframe.style.bottom = "0"
    iframe.style.width = "0"
    iframe.style.height = "0"
    iframe.style.border = "0"
    document.body.appendChild(iframe)
    const doc = iframe.contentWindow?.document
    if (!doc) return
    doc.open()
    doc.write(html)
    doc.close()
    iframe.onload = () => {
      iframe.contentWindow?.focus()
      iframe.contentWindow?.print()
      setTimeout(() => iframe.remove(), 1000)
    }
    return
  }

  printWindow.document.open()
  printWindow.document.write(html)
  printWindow.document.close()
  window.setTimeout(() => {
    printWindow.document.title = filename.replace(/\.pdf$/i, "")
    printWindow.focus()
    printWindow.print()
  }, 250)
}

function buildReportHtml(input: ReportPdfInput, filename: string) {
  const isRtl = input.language?.startsWith("ar")
  const docDir = isRtl ? "rtl" : "ltr"
  const startAlign = isRtl ? "right" : "left"
  const endAlign = isRtl ? "left" : "right"
  const generatedAt = formatPdfDate(input.generatedAt || new Date(), input.language)
  const generatedBy = input.generatedBy || "-"
  const filters = input.filters.length ? input.filters : [{ label: "-", value: "-" }]
  const metrics = input.metrics.length ? input.metrics : [{ label: input.labels.rows, value: String(input.rows.length) }]
  const visibleColumns = input.columns.slice(0, 10)

  return `<!doctype html>
<html lang="${escapeHtml(input.language || "ar")}" dir="${docDir}">
<head>
  <meta charset="utf-8" />
  <title>${escapeHtml(filename.replace(/\.pdf$/i, ""))}</title>
  <style>
    @page {
      size: A4 landscape;
      margin: 0;
    }

    * {
      box-sizing: border-box;
      -webkit-print-color-adjust: exact;
      print-color-adjust: exact;
    }

    body {
      margin: 0;
      background: #f3efe7;
      color: #111827;
      font-family: Cairo, Arial, "Segoe UI", Tahoma, sans-serif;
    }

    .page {
      width: 297mm;
      min-height: 210mm;
      margin: 0 auto;
      padding: 10mm;
      direction: ${docDir};
      background:
        linear-gradient(180deg, rgba(184, 137, 19, 0.08), transparent 30%),
        #f7f2e8;
    }

    .sheet {
      min-height: 190mm;
      overflow: hidden;
      border: 1px solid #d6bd76;
      background: #fffdf8;
      box-shadow: 0 18px 45px rgba(20, 23, 31, 0.16);
    }

    .hero {
      display: grid;
      grid-template-columns: 64px 1fr auto;
      gap: 16px;
      align-items: center;
      padding: 18px 22px;
      color: white;
      background:
        linear-gradient(135deg, rgba(18, 24, 33, 0.98), rgba(62, 50, 18, 0.95) 48%, rgba(181, 132, 13, 0.98));
      border-bottom: 4px solid #d8a719;
      direction: ${docDir};
    }

    .logo {
      display: grid;
      place-items: center;
      width: 52px;
      height: 52px;
      border: 2px solid rgba(255, 255, 255, 0.3);
      background: #f4ca4f;
      color: #1f2933;
      font-size: 18px;
      font-weight: 800;
      letter-spacing: 0;
    }

    .title {
      margin: 0;
      font-size: 23px;
      line-height: 1.15;
      font-weight: 800;
      letter-spacing: 0;
      text-align: ${startAlign};
    }

    .subtitle {
      max-width: 130mm;
      margin-top: 6px;
      color: #f8e8b4;
      font-size: 11px;
      font-weight: 700;
      line-height: 1.5;
      text-align: ${startAlign};
    }

    .code {
      display: inline-block;
      margin-top: 7px;
      color: white;
      font-size: 11px;
      font-weight: 800;
      direction: ltr;
      unicode-bidi: isolate;
    }

    .generated {
      min-width: 155px;
      text-align: ${endAlign};
      color: #fff8dc;
      font-size: 10px;
      font-weight: 800;
      direction: ${docDir};
    }

    .generated strong {
      display: block;
      margin-top: 5px;
      color: white;
      font-size: 12px;
      line-height: 1.4;
    }

    .band {
      display: grid;
      grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr);
      gap: 14px;
      margin: 16px 18px 0;
    }

    .panel {
      border: 1px solid #ead8a9;
      background: #fffaf0;
    }

    .panel-title {
      display: flex;
      align-items: center;
      gap: 8px;
      margin: 0;
      padding: 10px 12px;
      border-bottom: 1px solid #ead8a9;
      color: #111827;
      font-size: 13px;
      font-weight: 800;
    }

    .panel-title::before {
      content: "";
      width: 4px;
      height: 16px;
      background: #b88913;
    }

    .filters {
      display: grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 0;
    }

    .filter {
      min-height: 42px;
      padding: 8px 11px;
      border-bottom: 1px solid #f0e7cf;
    }

    .filter:nth-child(odd) {
      border-inline-end: 1px solid #f0e7cf;
    }

    .filter-label {
      color: #766846;
      font-size: 9.5px;
      font-weight: 800;
    }

    .filter-value {
      margin-top: 3px;
      color: #111827;
      font-size: 11px;
      font-weight: 800;
      overflow-wrap: anywhere;
      direction: auto;
      unicode-bidi: plaintext;
    }

    .metrics {
      display: grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 10px;
      padding: 12px;
    }

    .metric {
      min-height: 60px;
      padding: 11px;
      border: 1px solid #e0d0a6;
      background: white;
    }

    .metric-label {
      color: #766846;
      font-size: 9.5px;
      font-weight: 800;
      text-transform: uppercase;
      letter-spacing: 0;
    }

    .metric-value {
      margin-top: 7px;
      color: #111827;
      font-size: 18px;
      line-height: 1.15;
      font-weight: 800;
      overflow-wrap: anywhere;
      direction: auto;
      unicode-bidi: plaintext;
    }

    .section {
      margin: 16px 18px 0;
    }

    .section-head {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      color: #111827;
      font-size: 13px;
      font-weight: 800;
    }

    .row-count {
      color: #766846;
      font-size: 10px;
      direction: ltr;
      unicode-bidi: isolate;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      table-layout: fixed;
      border: 1px solid #eadfbe;
      direction: ${docDir};
    }

    thead th {
      padding: 9px 8px;
      border-bottom: 1px solid #d9c689;
      background: #efe2bb;
      color: #5d4810;
      font-size: 10px;
      font-weight: 900;
      text-align: ${startAlign};
      overflow-wrap: anywhere;
    }

    tbody tr:nth-child(odd) {
      background: #fffaf0;
    }

    tbody tr:nth-child(even) {
      background: #ffffff;
    }

    td {
      padding: 8px;
      border-bottom: 1px solid #f0e7cf;
      color: #111827;
      font-size: 10px;
      line-height: 1.45;
      font-weight: 700;
      vertical-align: top;
      overflow-wrap: anywhere;
      direction: auto;
      unicode-bidi: plaintext;
    }

    .align-start {
      text-align: ${startAlign};
    }

    .align-end {
      text-align: ${endAlign};
    }

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

    .empty {
      padding: 28px;
      color: #766846;
      text-align: center;
      font-size: 12px;
      font-weight: 800;
    }

    .footer {
      display: flex;
      justify-content: space-between;
      margin: 14px 18px 0;
      padding-top: 10px;
      border-top: 1px solid #e7dcc1;
      color: #766846;
      font-size: 10px;
      font-weight: 700;
      direction: ${docDir};
    }

    @media print {
      body {
        background: white;
      }

      .page {
        width: auto;
        min-height: auto;
        padding: 8mm;
        background: #f7f2e8;
      }

      .sheet {
        box-shadow: none;
      }

      .band,
      .section,
      .footer {
        break-inside: avoid;
      }
    }
  </style>
</head>
<body>
  <main class="page">
    <section class="sheet">
      <header class="hero">
        <div class="logo">GW</div>
        <div>
          <h1 class="title">${escapeHtml(input.title)}</h1>
          <div class="subtitle">${escapeHtml(input.subtitle)}</div>
          <div class="code">${escapeHtml(input.reportCode)}</div>
        </div>
        <div class="generated">
          ${escapeHtml(input.labels.generated)}
          <strong>${escapeHtml(generatedAt)}</strong>
          ${escapeHtml(input.labels.generatedBy)}
          <strong>${escapeHtml(generatedBy)}</strong>
        </div>
      </header>

      <section class="band">
        <div class="panel">
          <h2 class="panel-title">${escapeHtml(input.labels.filters)}</h2>
          <div class="filters">
            ${filters.map((filter) => `
              <div class="filter">
                <div class="filter-label">${escapeHtml(filter.label)}</div>
                <div class="filter-value">${escapeHtml(filter.value || "-")}</div>
              </div>
            `).join("")}
          </div>
        </div>

        <div class="panel">
          <h2 class="panel-title">${escapeHtml(input.labels.summary)}</h2>
          <div class="metrics">
            ${metrics.map((metric) => `
              <article class="metric">
                <div class="metric-label">${escapeHtml(metric.label)}</div>
                <div class="metric-value">${escapeHtml(metric.value)}</div>
              </article>
            `).join("")}
          </div>
        </div>
      </section>

      <section class="section">
        <div class="section-head">
          <span>${escapeHtml(input.labels.results)}</span>
          <span class="row-count">${escapeHtml(input.labels.rows)}: ${input.rows.length}</span>
        </div>
        ${input.rows.length ? `
          <table>
            <thead>
              <tr>
                ${visibleColumns.map((column) => `<th class="${alignClass(column.align)}">${escapeHtml(column.label)}</th>`).join("")}
              </tr>
            </thead>
            <tbody>
              ${input.rows.map((row) => `
                <tr>
                  ${visibleColumns.map((column) => `<td class="${alignClass(column.align)}">${escapeHtml(row[column.key] || "-")}</td>`).join("")}
                </tr>
              `).join("")}
            </tbody>
          </table>
        ` : `<div class="empty">${escapeHtml(input.labels.noData)}</div>`}
      </section>

      <footer class="footer">
        <span>${escapeHtml(input.labels.dashboard)}</span>
        <span>${escapeHtml(input.labels.confidential)}</span>
      </footer>
    </section>
  </main>
</body>
</html>`
}

function alignClass(align?: ReportPdfColumn["align"]) {
  if (align === "center") return "align-center"
  if (align === "end") return "align-end"
  return "align-start"
}

function formatPdfDate(value: string | Date, language: string) {
  const date = typeof value === "string" ? new Date(value) : value
  if (Number.isNaN(date.getTime())) return "-"
  return new Intl.DateTimeFormat(language?.startsWith("ar") ? "ar" : "en-US", {
    year: "numeric",
    month: "short",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  }).format(date)
}

function escapeHtml(value: string | number | null | undefined) {
  return String(value ?? "-")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;")
}
