import { formatDzdAmount } from "./formatters.js";
import { launchPuppeteerBrowser } from "./puppeteer.js";

const escapeHtml = (value) =>
  String(value ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");

const formatDate = (value) => {
  if (!value) {
    return "—";
  }

  const normalized = String(value);
  const [year, month, day] = normalized.split("-");

  if (year && month && day) {
    return `${day}/${month}/${year}`;
  }

  const parsed = new Date(normalized);
  return Number.isNaN(parsed.getTime())
    ? normalized
    : new Intl.DateTimeFormat("fr-FR").format(parsed);
};

const amount = (value) => escapeHtml(formatDzdAmount(value));

const renderRows = (rows = [], columns = []) =>
  rows
    .map(
      (row) => `
        <tr>
          ${columns
            .map((column) => {
              const value = row[column.key];
              const cellValue =
                column.type === "amount"
                  ? amount(value)
                  : escapeHtml(value || "—");

              return `<td class="${column.type === "amount" ? "amount" : ""}">${cellValue}</td>`;
            })
            .join("")}
        </tr>
      `,
    )
    .join("");

const buildHtml = ({ company, profile, declaration, previousPrecompte, generatedBy }) => {
  const part1To5Total =
    Number(declaration.total_cadre1 || 0) +
    Number(declaration.total_cadre2 || 0) +
    Number(declaration.total_cadre3 || 0) +
    Number(declaration.total_cadre4 || 0) +
    Number(declaration.total_cadre5 || 0);
  const recapRows = [
    {
      no: "1",
      nature: "IRG / Retenues a la source",
      compte: "C/201001/L1 a L8",
      montant:
        Number(declaration.total_cadre4 || 0) -
        Number(declaration.irg_retenues_detail?.e1l20?.amount || 0),
    },
    {
      no: "2",
      nature: "Revenus de capitaux mobiliers",
      compte: "C/201001/L1 a L8",
      montant: 0,
    },
    {
      no: "3",
      nature: "Revenus locatifs",
      compte: "C/201001/L1 a L8",
      montant: 0,
    },
    {
      no: "4",
      nature: "IRG / Traitements et salaires",
      compte: "C/201001/L1 a L8",
      montant: declaration.irg_retenues_detail?.e1l20?.amount || 0,
    },
    {
      no: "5",
      nature: "IRG / Professionnel (BIC/BNC)",
      compte: "C/201001/L1 a L8",
      montant: declaration.total_cadre3 || 0,
    },
    {
      no: "6",
      nature: "IBS",
      compte: "C/201001/M1 a M3",
      montant:
        Number(declaration.total_cadre1 || 0) + Number(declaration.total_cadre2 || 0),
    },
    {
      no: "7",
      nature: "Taxe Locale de Solidarite",
      compte: "C/...",
      montant: declaration.total_cadre5 || 0,
    },
    {
      no: "8",
      nature: "Droits et taxes indirects",
      compte: "C/500020",
      montant: declaration.total_cadre7 || 0,
    },
    {
      no: "9",
      nature: "Droits de timbre",
      compte: "C/201002",
      montant: declaration.total_cadre6 || 0,
    },
    {
      no: "10",
      nature: "Autres taxes",
      compte: "C/...",
      montant: declaration.total_cadre7 || 0,
    },
    {
      no: "11",
      nature: "TVA a payer",
      compte: "C/500020",
      montant: declaration.total_cadre8 || 0,
    },
  ];

  return `
    <!DOCTYPE html>
    <html lang="fr">
      <head>
        <meta charset="utf-8" />
        <title>G50 ${escapeHtml(declaration.period_label)}</title>
        <style>
          * { box-sizing: border-box; }
          body {
            margin: 0;
            background: #eef2f7;
            color: #0f172a;
            font-family: Arial, sans-serif;
            font-size: 11px;
            line-height: 1.45;
          }
          .page { padding: 16px 18px 20px; }
          .sheet {
            background: #fff;
            border: 1px solid #cbd5e1;
            border-radius: 18px;
            overflow: hidden;
            box-shadow: 0 20px 45px rgba(15, 23, 42, 0.08);
          }
          .sheet-header {
            padding: 18px 22px 16px;
            background: linear-gradient(135deg, rgba(37,99,235,0.12), rgba(255,255,255,0.94)), #f8fafc;
            border-bottom: 1px solid #cbd5e1;
          }
          .title {
            margin: 12px 0 0;
            color: #1d4ed8;
            font-size: 18px;
            font-weight: 800;
            text-transform: uppercase;
          }
          .subtitle, .small {
            margin: 6px 0 0;
            color: #475569;
            font-size: 10px;
          }
          .header-grid, .info-grid, .summary-grid, .payment-grid {
            display: grid;
            gap: 12px;
          }
          .header-grid, .info-grid { grid-template-columns: 1fr 1fr; }
          .summary-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
          .payment-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
          .box {
            border: 1px solid #cbd5e1;
            border-radius: 12px;
            padding: 10px 12px;
            background: #fff;
          }
          .box strong { display: block; color: #0f172a; }
          .section {
            padding: 16px 22px 18px;
            border-top: 1px solid #e2e8f0;
          }
          .section-title {
            display: flex;
            justify-content: space-between;
            gap: 16px;
            align-items: baseline;
            margin-bottom: 12px;
          }
          .section-title h2 {
            margin: 0;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.08em;
          }
          .arabic {
            direction: rtl;
            font-family: Tahoma, Arial, sans-serif;
          }
          table {
            width: 100%;
            border-collapse: collapse;
          }
          th, td {
            border: 1px solid #cbd5e1;
            padding: 7px 8px;
            vertical-align: top;
          }
          th {
            background: #0f172a;
            color: #f8fafc;
            font-size: 9px;
            text-transform: uppercase;
            letter-spacing: 0.08em;
          }
          .amount {
            text-align: right;
            white-space: nowrap;
            font-family: "Courier New", monospace;
          }
          .total-row td {
            background: #eff6ff;
            font-weight: 800;
          }
          .grand-total {
            border: 1px solid #fcd34d;
            background: #fffbeb;
            color: #92400e;
            border-radius: 14px;
            padding: 14px 16px;
            font-size: 16px;
            font-weight: 800;
            text-align: right;
          }
          .note {
            margin-top: 10px;
            padding: 10px 12px;
            border-radius: 12px;
            border: 1px solid #dbeafe;
            background: #eff6ff;
            color: #1e3a8a;
          }
        </style>
      </head>
      <body>
        <div class="page">
          <div class="sheet">
            <div class="sheet-header">
              <div class="header-grid">
                <div>
                  <p class="small">Direction Generale des Impots</p>
                  <p class="small">Declaration tenant lieu de bordereau - avis de versement</p>
                </div>
                <div style="text-align:right;">
                  <p class="small arabic">المديرية العامة للضرائب</p>
                  <p class="small arabic">التصريح الذي يقوم مقام جدول الإشعار بالدفع</p>
                </div>
              </div>
              <h1 class="title">Serie G n°50 - ${escapeHtml(declaration.period_label)}</h1>
              <p class="subtitle">
                NIF ${escapeHtml(declaration.nif || company.nif || "—")} ·
                AI ${escapeHtml(declaration.article_imposition || company.ai || "—")} ·
                ${escapeHtml(company.name || "Societe")}
              </p>
            </div>

            <section class="section">
              <div class="section-title">
                <h2>Identification</h2>
                <span class="arabic">التعريف</span>
              </div>
              <div class="info-grid">
                <div class="box"><strong>Nom / Raison sociale</strong>${escapeHtml(company.name || "—")}</div>
                <div class="box"><strong>Activite</strong>${escapeHtml(profile?.activity_description || "—")}</div>
                <div class="box"><strong>NIN / NIF / Article</strong>NIN ${escapeHtml(declaration.nin || profile?.nin || "—")} · NIF ${escapeHtml(declaration.nif || "—")} · AI ${escapeHtml(declaration.article_imposition || "—")}</div>
                <div class="box"><strong>Code activite / Forme juridique</strong>${escapeHtml(declaration.code_activite || "—")} · ${escapeHtml(declaration.forme_juridique || "—")}</div>
                <div class="box" style="grid-column:1 / -1;"><strong>Adresse</strong>${escapeHtml(company.address || "—")}</div>
              </div>
            </section>

            <section class="section">
              <div class="section-title"><h2>Cadres 1 a 5</h2><span>${amount(part1To5Total)}</span></div>
              <div class="summary-grid">
                <div class="box"><strong>Cadre 1</strong>${amount(declaration.total_cadre1 || 0)}</div>
                <div class="box"><strong>Cadre 2</strong>${amount(declaration.total_cadre2 || 0)}</div>
                <div class="box"><strong>Cadre 3</strong>${amount(declaration.total_cadre3 || 0)}</div>
                <div class="box"><strong>Cadre 4</strong>${amount(declaration.total_cadre4 || 0)}</div>
                <div class="box"><strong>Cadre 5</strong>${amount(declaration.total_cadre5 || 0)}</div>
              </div>
            </section>

            <section class="section">
              <div class="section-title">
                <h2>Cadre 6 - Droit de timbre</h2>
                <span class="arabic">حقوق الطابع</span>
              </div>
              <table>
                <thead>
                  <tr><th>Code</th><th>Operations imposables</th><th>CA imposable</th><th>Taux</th><th>Montant</th></tr>
                </thead>
                <tbody>
                  ${renderRows(declaration.droits_timbre_detail?.rows || [], [
                    { key: "code" },
                    { key: "label" },
                    { key: "base", type: "amount" },
                    { key: "rate" },
                    { key: "amount", type: "amount" },
                  ])}
                  <tr class="total-row"><td colspan="4">6 TOTAL</td><td class="amount">${amount(declaration.total_cadre6 || 0)}</td></tr>
                </tbody>
              </table>
            </section>

            <section class="section">
              <div class="section-title">
                <h2>Cadre 7 - Autres taxes</h2>
                <span class="arabic">ضرائب أخرى</span>
              </div>
              <table>
                <thead>
                  <tr><th>Code</th><th>Impots et taxes</th><th>Base</th><th>Taux</th><th>Montant</th></tr>
                </thead>
                <tbody>
                  ${renderRows(declaration.autres_taxes_detail?.rows || [], [
                    { key: "code" },
                    { key: "label" },
                    { key: "base", type: "amount" },
                    { key: "rate" },
                    { key: "amount", type: "amount" },
                  ])}
                  <tr class="total-row"><td colspan="4">7 TOTAL</td><td class="amount">${amount(declaration.total_cadre7 || 0)}</td></tr>
                </tbody>
              </table>
            </section>

            <section class="section">
              <div class="section-title">
                <h2>Cadre 8 - TVA</h2>
                <span class="arabic">الرسم على القيمة المضافة</span>
              </div>
              <div class="note">Les chiffres d'affaires sont ramenes au zero au dernier chiffre avant calcul des droits.</div>
              <table style="margin-top:12px;">
                <thead>
                  <tr><th>Code</th><th>Operation</th><th>CA Total</th><th>CA Exonere</th><th>CA Imposable</th><th>Taux</th><th>Droits dus</th></tr>
                </thead>
                <tbody>
                  ${renderRows(
                    [
                      ...(declaration.tva_ca_imposable_detail?.rows9 || []),
                      ...(declaration.tva_ca_imposable_detail?.rows19 || []),
                    ],
                    [
                      { key: "code" },
                      { key: "label" },
                      { key: "ca_total", type: "amount" },
                      { key: "ca_exonere", type: "amount" },
                      { key: "ca_imposable", type: "amount" },
                      { key: "rate" },
                      { key: "montant_droits", type: "amount" },
                    ],
                  )}
                  <tr class="total-row"><td colspan="6">Droits dus</td><td class="amount">${amount(declaration.tva_total_droits || 0)}</td></tr>
                </tbody>
              </table>
              <table style="margin-top:12px;">
                <thead>
                  <tr><th>Code</th><th>Nature de la deduction</th><th>Montant</th></tr>
                </thead>
                <tbody>
                  ${renderRows(
                    [
                      { code: "E3B91", label: "Precompte anterieur", amount: declaration.tva_deductions_detail?.e3b91 || 0 },
                      { code: "E3B92", label: "TVA sur achats biens, matieres et services", amount: declaration.tva_deductions_detail?.e3b92 || 0 },
                      { code: "E3B93", label: "TVA sur achats biens amortissables", amount: declaration.tva_deductions_detail?.e3b93 || 0 },
                      { code: "E3B94", label: "Regularisation prorata - deduction complementaire", amount: declaration.tva_deductions_detail?.e3b94 || 0 },
                      { code: "E3B95", label: "TVA a recuperer sur factures annulees ou impayees", amount: declaration.tva_deductions_detail?.e3b95 || 0 },
                      { code: "E3B96", label: "Autres deductions", amount: declaration.tva_deductions_detail?.e3b96 || 0 },
                    ],
                    [
                      { key: "code" },
                      { key: "label" },
                      { key: "amount", type: "amount" },
                    ],
                  )}
                  <tr class="total-row"><td colspan="2">Total deductions</td><td class="amount">${amount(declaration.tva_total_deductions || 0)}</td></tr>
                </tbody>
              </table>
              <div class="summary-grid" style="margin-top:12px;">
                <div class="box"><strong>Regularisation prorata (+)</strong>${amount(declaration.tva_deductions_detail?.e3b97 || 0)}</div>
                <div class="box"><strong>Reversement art. 38 (+)</strong>${amount(declaration.tva_deductions_detail?.e3b98 || 0)}</div>
                <div class="box"><strong>TVA a payer</strong>${amount(declaration.tva_a_payer || 0)}</div>
                <div class="box"><strong>Precompte a reporter</strong>${amount(declaration.tva_precompte_reporter || 0)}</div>
              </div>
              <p class="subtitle">Precompte precedent: ${amount(previousPrecompte?.amount || 0)} ${previousPrecompte?.period_label ? `· source ${escapeHtml(previousPrecompte.period_label)}` : ""}</p>
            </section>

            <section class="section">
              <div class="section-title">
                <h2>Recapitulation finale</h2>
                <span class="arabic">الملخص النهائي</span>
              </div>
              <table>
                <thead>
                  <tr><th>N°</th><th>Nature</th><th>Compte comptable</th><th>Montant</th></tr>
                </thead>
                <tbody>
                  ${renderRows(recapRows, [
                    { key: "no" },
                    { key: "nature" },
                    { key: "compte" },
                    { key: "montant", type: "amount" },
                  ])}
                </tbody>
              </table>
              <div class="grand-total" style="margin-top:14px;">
                Montant total a payer: ${amount(declaration.total_a_payer || 0)}
              </div>
            </section>

            <section class="section">
              <div class="section-title">
                <h2>Paiement et certification</h2>
                <span class="arabic">الدفع والتصديق</span>
              </div>
              <div class="payment-grid">
                <div class="box">
                  <strong>Paiement</strong>
                  Cheque bancaire: ${escapeHtml(declaration.cheque_bancaire_no || "—")}<br />
                  Agence: ${escapeHtml(declaration.cheque_bancaire_agence || "—")}<br />
                  Cheque postal: ${escapeHtml(declaration.cheque_postal_no || "—")}<br />
                  Numeraire: ${amount(declaration.montant_numeraire || 0)}<br />
                  Quittance: ${escapeHtml(declaration.quittance_numero || "—")} du ${escapeHtml(formatDate(declaration.quittance_date))}
                </div>
                <div class="box">
                  <strong>Certification</strong>
                  A ${escapeHtml(declaration.lieu_declaration || company.city || "—")} le ${escapeHtml(formatDate(declaration.date_signature))}<br />
                  Certifie sincere et veritable le contenu de la presente declaration.
                </div>
              </div>
              ${
                declaration.observations
                  ? `<div class="note">Observations: ${escapeHtml(declaration.observations)}</div>`
                  : ""
              }
              <p class="subtitle">Document genere le ${escapeHtml(formatDate(new Date().toISOString()))} par ${escapeHtml(generatedBy)}.</p>
            </section>
          </div>
        </div>
      </body>
    </html>
  `;
};

export const buildG50PdfBuffer = async ({
  company,
  profile,
  declaration,
  previousPrecompte,
  generatedBy,
}) => {
  const browser = await launchPuppeteerBrowser();

  try {
    const page = await browser.newPage();
    await page.setContent(
      buildHtml({
        company,
        profile,
        declaration,
        previousPrecompte,
        generatedBy,
      }),
      { waitUntil: "networkidle0" },
    );

    return await page.pdf({
      format: "A4",
      printBackground: true,
      displayHeaderFooter: true,
      headerTemplate: `
        <div style="width:100%;padding:0 10px;font-size:9px;font-family:Arial,sans-serif;color:#475569;">
          <div style="display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #CBD5E1;padding-bottom:6px;">
            <span style="font-weight:700;color:#1D4ED8;">G50</span>
            <span>${escapeHtml(company.name || "Societe")}</span>
          </div>
        </div>
      `,
      footerTemplate: `
        <div style="width:100%;padding:0 10px;font-size:9px;font-family:Arial,sans-serif;color:#475569;">
          <div style="display:flex;justify-content:space-between;align-items:center;border-top:1px solid #CBD5E1;padding-top:6px;">
            <span>Document genere par ${escapeHtml(generatedBy || "Systeme")}</span>
            <span>Page <span class="pageNumber"></span> / <span class="totalPages"></span></span>
          </div>
        </div>
      `,
      margin: {
        top: "20mm",
        right: "10mm",
        bottom: "18mm",
        left: "10mm",
      },
    });
  } finally {
    await browser.close();
  }
};
