import { formatMoney, formatNumber } from "@/lib/format"

export type CustomerProfilePdfInput = {
  customer: any
  cashWallet: any
  goldWallet: any
  statusLabel: string
  kycLabel: string
  primaryBranchName: string
  registeredBranchName: string
  language: string
  labels: CustomerProfilePdfLabels
}

export type CustomerProfilePdfLabels = {
  title: string
  generated: string
  subtitle: string
  profileInformation: string
  customerCode: string
  fullName: string
  email: string
  phone: string
  status: string
  kycLevel: string
  identityType: string
  identityNumber: string
  identityExpiry: string
  primaryBranch: string
  registeredBranch: string
  createdAt: string
  lastLogin: string
  cashAvailable: string
  cashReserved: string
  goldAvailable: string
  goldReserved: string
  goldUnit: string
  dashboard: string
  confidential: string
}

export function printCustomerProfilePdf(input: CustomerProfilePdfInput, filename: string) {
  const html = buildCustomerProfileHtml(input, filename)
  const printWindow = window.open("", "_blank", "width=900,height=1100")

  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)
}

export function branchDisplayName(id: string | null | undefined, lookup: Record<string, string>) {
  if (!id) return "-"
  return truncateText(lookup[id] || shortId(id), 38)
}

function buildCustomerProfileHtml({
  customer,
  cashWallet,
  goldWallet,
  statusLabel,
  kycLabel,
  primaryBranchName,
  registeredBranchName,
  language,
  labels,
}: CustomerProfilePdfInput, filename: string) {
  const displayName = customer.name || customer.full_name_ar || customer.email || customer.phone || customer.user_id?.slice(0, 8) || "-"
  const customerCode = customer.customer_code || `CUST-${String(customer.id || "").slice(0, 8).toUpperCase()}`
  const generatedAt = formatPdfDate(new Date(), language)
  const isRtl = language?.startsWith("ar")
  const docDir = isRtl ? "rtl" : "ltr"
  const tableDir = isRtl ? "rtl" : "ltr"
  const startAlign = isRtl ? "right" : "left"
  const endAlign = isRtl ? "left" : "right"
  const rows: [string, string][] = [
    [labels.customerCode, customerCode],
    [labels.fullName, displayName],
    [labels.email, customer.email || "-"],
    [labels.phone, customer.phone || "-"],
    [labels.status, statusLabel || customer.status || "-"],
    [labels.kycLevel, kycLabel || customer.kyc_level || "-"],
    [labels.identityType, customer.identity_type || "-"],
    [labels.identityNumber, customer.identity_number || "-"],
    [labels.identityExpiry, customer.identity_expiry_date ? formatPdfDate(customer.identity_expiry_date, language) : "-"],
    [labels.primaryBranch, primaryBranchName],
    [labels.registeredBranch, registeredBranchName],
    [labels.createdAt, customer.created_at ? formatPdfDate(customer.created_at, language) : "-"],
    [labels.lastLogin, customer.last_login_at ? formatPdfDate(customer.last_login_at, language) : "-"],
  ]
  const metrics: [string, string][] = [
    [labels.cashAvailable, formatMoney(cashWallet?.available_balance ?? customer.cash_wallets?.[0]?.available_balance ?? 0)],
    [labels.cashReserved, formatMoney(cashWallet?.reserved_balance ?? customer.cash_wallets?.[0]?.reserved_balance ?? 0)],
    [labels.goldAvailable, `${formatNumber(goldWallet?.available_grams ?? customer.gold_wallets?.[0]?.available_grams ?? 0, 2)} ${labels.goldUnit}`],
    [labels.goldReserved, `${formatNumber(goldWallet?.reserved_grams ?? customer.gold_wallets?.[0]?.reserved_grams ?? 0, 2)} ${labels.goldUnit}`],
  ]

  return `<!doctype html>
<html lang="${escapeHtml(language || "ar")}" dir="${docDir}">
<head>
  <meta charset="utf-8" />
  <title>${escapeHtml(filename.replace(/\.pdf$/i, ""))}</title>
  <style>
    @page {
      size: A4;
      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: 210mm;
      min-height: 297mm;
      margin: 0 auto;
      padding: 14mm;
      direction: ${docDir};
      background:
        linear-gradient(180deg, rgba(184, 137, 19, 0.08), transparent 28%),
        #f7f2e8;
    }

    .sheet {
      min-height: 269mm;
      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: 72px 1fr auto;
      gap: 16px;
      align-items: center;
      padding: 22px 26px;
      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: 58px;
      height: 58px;
      border: 2px solid rgba(255, 255, 255, 0.3);
      background: #f4ca4f;
      color: #1f2933;
      font-size: 20px;
      font-weight: 800;
      letter-spacing: 0;
    }

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

    .code {
      display: block;
      width: 100%;
      margin-top: 8px;
      color: #f8e8b4;
      font-size: 12px;
      font-weight: 700;
      direction: ltr;
      text-align: ${startAlign};
      unicode-bidi: isolate;
    }

    .generated {
      min-width: 130px;
      text-align: ${endAlign};
      color: #fff8dc;
      font-size: 11px;
      font-weight: 700;
      direction: ${docDir};
    }

    .generated span {
      display: block;
      margin-top: 6px;
      color: white;
      font-size: 12px;
      font-weight: 800;
    }

    .summary {
      display: grid;
      grid-template-columns: 1fr auto;
      gap: 16px;
      align-items: center;
      margin: 20px 22px 0;
      padding: 16px 18px;
      border: 1px solid #ead8a9;
      background: #fff8e7;
      direction: ${docDir};
    }

    .name {
      margin: 0;
      font-size: 21px;
      font-weight: 800;
      line-height: 1.35;
      overflow-wrap: anywhere;
      direction: auto;
      text-align: start;
    }

    .subtitle {
      margin-top: 4px;
      color: #6b7280;
      font-size: 11px;
      font-weight: 600;
    }

    .status {
      min-width: 86px;
      padding: 7px 12px;
      border: 1px solid #b88913;
      background: #f4ca4f;
      color: #1f2933;
      font-size: 11px;
      font-weight: 800;
      text-align: center;
      direction: auto;
    }

    .metrics {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 10px;
      margin: 16px 22px 0;
      direction: ${tableDir};
    }

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

    .metric-label {
      color: #766846;
      font-size: 10px;
      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;
    }

    .section {
      margin: 20px 22px 0;
    }

    .section-title {
      display: flex;
      align-items: center;
      gap: 10px;
      margin: 0 0 10px;
      color: #111827;
      font-size: 15px;
      font-weight: 800;
    }

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

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

    .info-table tr:nth-child(odd) {
      background: #fffaf0;
    }

    .info-table tr:nth-child(even) {
      background: #ffffff;
    }

    .info-table th,
    .info-table td {
      padding: 8px 12px;
      border-bottom: 1px solid #f0e7cf;
      vertical-align: top;
      font-size: 11.5px;
      line-height: 1.45;
    }

    .info-table th {
      width: 34%;
      color: #6f5b19;
      font-weight: 800;
      text-align: ${startAlign};
    }

    .info-table td {
      color: #111827;
      font-weight: 700;
      text-align: ${endAlign};
      overflow-wrap: anywhere;
      direction: auto;
      unicode-bidi: plaintext;
    }

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

    @media print {
      body {
        background: white;
      }

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

      .sheet {
        box-shadow: none;
      }
    }
  </style>
</head>
<body>
  <main class="page">
    <section class="sheet">
      <header class="hero">
        <div class="logo">GW</div>
        <div>
          <h1 class="title">${escapeHtml(labels.title)}</h1>
          <div class="code">${escapeHtml(customerCode)}</div>
        </div>
        <div class="generated">${escapeHtml(labels.generated)}<span>${escapeHtml(generatedAt)}</span></div>
      </header>

      <section class="summary">
        <div>
          <h2 class="name">${escapeHtml(displayName)}</h2>
          <div class="subtitle">${escapeHtml(labels.subtitle)}</div>
        </div>
        <div class="status">${escapeHtml(statusLabel || customer.status || "-")}</div>
      </section>

      <section class="metrics">
        ${metrics.map(([label, value]) => `
          <article class="metric">
            <div class="metric-label">${escapeHtml(label)}</div>
            <div class="metric-value">${escapeHtml(value)}</div>
          </article>
        `).join("")}
      </section>

      <section class="section">
        <h3 class="section-title">${escapeHtml(labels.profileInformation)}</h3>
        <table class="info-table">
          <tbody>
            ${rows.map(([label, value]) => `
              <tr>
                <th>${escapeHtml(label)}</th>
                <td>${escapeHtml(value)}</td>
              </tr>
            `).join("")}
          </tbody>
        </table>
      </section>

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

function truncateText(value: string, maxLength: number) {
  const text = String(value || "-")
  if (text.length <= maxLength) return text
  if (maxLength <= 8) return text.slice(0, maxLength)
  const head = Math.ceil((maxLength - 3) * 0.58)
  const tail = Math.floor((maxLength - 3) * 0.42)
  return `${text.slice(0, head)}...${text.slice(text.length - tail)}`
}

function shortId(value: string | null | undefined) {
  if (!value) return "-"
  return truncateText(value, 24)
}

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) {
  return String(value ?? "-")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;")
}
