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 date = new Date(normalized);

  if (Number.isNaN(date.getTime())) {
    return normalized;
  }

  return new Intl.DateTimeFormat("fr-FR").format(date);
};

const renderCheckbox = (checked, labelFr, labelAr = "") => `
  <div class="checkbox-line">
    <span class="checkbox-box ${checked ? "checked" : ""}">${checked ? "✓" : ""}</span>
    <span>${escapeHtml(labelFr)}</span>
    ${labelAr ? `<span class="arabic">${escapeHtml(labelAr)}</span>` : ""}
  </div>
`;

const buildHtml = ({ company, profile, declaration, generatedBy }) => {
  const totalCa =
    Number(declaration.ca_marchandises_global || 0) +
    Number(declaration.ca_services_global || 0) +
    Number(declaration.ca_auto_entrepreneur_global || 0);
  const exonerationFlags = new Set(declaration.exoneration_flags || []);
  const minimumApplies =
    Number(declaration.montant_effectif_a_payer || 0) >
    Number(declaration.total_ifu_du || 0) + 0.009;

  const paymentModeLabel =
    {
      integral: "Paiement intégral",
      fractionne: "Paiement fractionné",
      minimum: "Minimum d'imposition",
    }[declaration.mode_paiement] || declaration.mode_paiement;

  return `
    <!DOCTYPE html>
    <html lang="fr">
      <head>
        <meta charset="utf-8" />
        <title>GN12 ${escapeHtml(declaration.annee)}</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: #ffffff;
            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.10), rgba(255,255,255,0.92)),
              #f8fafc;
            border-bottom: 1px solid #cbd5e1;
          }
          .topline {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 16px;
          }
          .org-block p,
          .meta-block p {
            margin: 0;
          }
          .org-block .small,
          .meta-block .small {
            font-size: 10px;
            color: #475569;
            text-transform: uppercase;
            letter-spacing: 0.12em;
          }
          .title-grid {
            display: grid;
            grid-template-columns: 1fr auto;
            gap: 16px;
            margin-top: 16px;
            align-items: end;
          }
          .main-title {
            margin: 0;
            font-size: 18px;
            line-height: 1.25;
            font-weight: 800;
            color: #1d4ed8;
            text-transform: uppercase;
          }
          .subtitle {
            margin: 6px 0 0;
            color: #475569;
            font-size: 11px;
          }
          .year-badge {
            padding: 10px 14px;
            border-radius: 14px;
            border: 1px solid #bfdbfe;
            background: #eff6ff;
            text-align: right;
          }
          .year-badge strong {
            display: block;
            font-size: 18px;
            color: #1d4ed8;
          }
          .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;
            color: #0f172a;
            text-transform: uppercase;
            letter-spacing: 0.08em;
          }
          .arabic {
            direction: rtl;
            font-family: "Tahoma", Arial, sans-serif;
          }
          .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px 14px;
          }
          .info-box {
            border: 1px solid #cbd5e1;
            border-radius: 12px;
            padding: 10px 12px;
            background: #ffffff;
            min-height: 54px;
          }
          .info-box.full {
            grid-column: 1 / -1;
          }
          .info-label {
            display: block;
            font-size: 10px;
            color: #475569;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            margin-bottom: 6px;
          }
          .info-value {
            font-weight: 700;
          }
          .checkbox-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 8px 12px;
          }
          .checkbox-line {
            display: flex;
            align-items: center;
            gap: 8px;
          }
          .checkbox-box {
            width: 16px;
            height: 16px;
            border: 1px solid #64748b;
            border-radius: 4px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            color: #1d4ed8;
            background: #ffffff;
          }
          .checkbox-box.checked {
            border-color: #1d4ed8;
            background: #eff6ff;
          }
          table {
            width: 100%;
            border-collapse: collapse;
          }
          th,
          td {
            border: 1px solid #cbd5e1;
            padding: 8px 9px;
            vertical-align: top;
          }
          th {
            background: #0f172a;
            color: #f8fafc;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            font-size: 9px;
          }
          .total-row td {
            background: #eff6ff;
            font-weight: 800;
          }
          .amount {
            text-align: right;
            font-family: "JetBrains Mono", "Courier New", monospace;
            white-space: nowrap;
          }
          .summary-grid {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 12px;
          }
          .summary-box {
            border: 1px solid #bfdbfe;
            border-radius: 14px;
            background: #f8fbff;
            padding: 12px 14px;
          }
          .summary-box.accent {
            background: #eff6ff;
            border-color: #93c5fd;
          }
          .summary-box.warning {
            background: #fffbeb;
            border-color: #fcd34d;
          }
          .summary-box .label {
            display: block;
            color: #475569;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            font-size: 10px;
          }
          .summary-box .value {
            display: block;
            margin-top: 8px;
            font-size: 16px;
            font-weight: 800;
            color: #0f172a;
            font-family: "JetBrains Mono", "Courier New", monospace;
          }
          .notice {
            margin-top: 12px;
            padding: 10px 12px;
            border-radius: 12px;
            border: 1px solid #fcd34d;
            background: #fffbeb;
            color: #92400e;
            font-size: 10px;
          }
          .payment-grid {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            gap: 12px;
          }
          .payment-card {
            border: 1px solid #cbd5e1;
            border-radius: 14px;
            background: #ffffff;
            padding: 12px 14px;
            min-height: 138px;
          }
          .payment-card.active {
            border-color: #60a5fa;
            background: #eff6ff;
          }
          .payment-card h3 {
            margin: 0 0 10px;
            font-size: 12px;
          }
          .payment-list {
            margin: 0;
            padding: 0;
            list-style: none;
          }
          .payment-list li + li {
            margin-top: 7px;
          }
          .signature-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 14px;
          }
          .signature-box {
            border: 1px dashed #94a3b8;
            border-radius: 14px;
            padding: 12px;
            min-height: 84px;
            background: #f8fafc;
          }
          .footer-note {
            margin-top: 10px;
            color: #475569;
            font-size: 10px;
          }
        </style>
      </head>
      <body>
        <div class="page">
          <div class="sheet">
            <div class="sheet-header">
              <div class="topline">
                <div class="org-block">
                  <p class="small">Direction des Impôts de Wilaya</p>
                  <p><strong>${escapeHtml(declaration.direction_wilaya || "—")}</strong></p>
                  <p class="subtitle">DIW: ${escapeHtml(declaration.diw || "—")} · Recette: ${escapeHtml(
                    declaration.recette || "—",
                  )} · Commune: ${escapeHtml(declaration.commune || "—")}</p>
                </div>
                <div class="meta-block" style="text-align:right;">
                  <p class="small">الجمهورية الجزائرية الديمقراطية الشعبية</p>
                  <p><strong class="arabic">تصريح تقديري لنظام الضريبة الجزافية الوحيدة</strong></p>
                </div>
              </div>
              <div class="title-grid">
                <div>
                  <h1 class="main-title">Declaration Previsionnelle - Regime IFU - Serie GN 12 (${escapeHtml(
                    declaration.annee,
                  )})</h1>
                  <p class="subtitle">Version numerique de la declaration annuelle estimee de l'impot forfaitaire unique.</p>
                </div>
                <div class="year-badge">
                  <span class="small">Annee / السنة</span>
                  <strong>${escapeHtml(declaration.annee)}</strong>
                </div>
              </div>
            </div>

            <section class="section">
              <div class="section-title">
                <h2>Section I - Identification</h2>
                <span class="arabic">القسم الأول - التعريف</span>
              </div>
              <div class="info-grid">
                <div class="info-box">
                  <span class="info-label">Nom / Raison sociale</span>
                  <div class="info-value">${escapeHtml(declaration.nom_raison_sociale || company.name || "—")}</div>
                </div>
                <div class="info-box">
                  <span class="info-label">Activites exercees</span>
                  <div class="info-value">${escapeHtml(declaration.activites_exercees || "—")}</div>
                </div>
                <div class="info-box">
                  <span class="info-label">Date debut d'activite</span>
                  <div class="info-value">${escapeHtml(formatDate(declaration.date_debut_activite))}</div>
                </div>
                <div class="info-box">
                  <span class="info-label">NIF / NIN / Article</span>
                  <div class="info-value">
                    NIF ${escapeHtml(profile?.nif || company.nif || "—")} · NIN ${escapeHtml(profile?.nin || "—")} · AI ${escapeHtml(profile?.article_imposition || company.ai || "—")}
                  </div>
                </div>
                <div class="info-box full">
                  <span class="info-label">Adresse lieu d'exercice</span>
                  <div class="info-value">${escapeHtml(declaration.adresse_lieu_exercice || company.address || "—")}</div>
                </div>
                <div class="info-box full">
                  <span class="info-label">Adresse domicile</span>
                  <div class="info-value">${escapeHtml(declaration.adresse_domicile || company.address || "—")}</div>
                </div>
                <div class="info-box full">
                  <span class="info-label">Activites exonerees</span>
                  <div class="checkbox-grid">
                    ${renderCheckbox(exonerationFlags.has("ANADE"), "ANADE", "أوناد")}
                    ${renderCheckbox(exonerationFlags.has("CNAC"), "CNAC", "كناك")}
                    ${renderCheckbox(exonerationFlags.has("ANGEM"), "ANGEM", "أنجام")}
                    ${renderCheckbox(exonerationFlags.has("artisanat"), "Artisanat", "الصناعة التقليدية")}
                    ${renderCheckbox(exonerationFlags.has("autre"), "Autres", "أخرى")}
                  </div>
                </div>
              </div>
            </section>

            <section class="section">
              <div class="section-title">
                <h2>Section II - Chiffre d'affaires previsionnel</h2>
                <span class="arabic">القسم الثاني - رقم الأعمال التقديري</span>
              </div>
              <table>
                <thead>
                  <tr>
                    <th>Nature d'activite</th>
                    <th>Taux</th>
                    <th>CA Global</th>
                    <th>CA Imposable</th>
                    <th>CA Exonere</th>
                    <th>IFU du (A)</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>Production / Vente de marchandises</td>
                    <td class="amount">5,00%</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_marchandises_global))}</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_marchandises_imposable))}</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_marchandises_exonere))}</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ifu_marchandises))}</td>
                  </tr>
                  <tr>
                    <td>Prestations de services / Autres activites</td>
                    <td class="amount">12,00%</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_services_global))}</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_services_imposable))}</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_services_exonere))}</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ifu_services))}</td>
                  </tr>
                  <tr>
                    <td>Activites auto-entrepreneur</td>
                    <td class="amount">0,50%</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_auto_entrepreneur_global))}</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_auto_entrepreneur_imposable))}</td>
                    <td class="amount">—</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ifu_auto_entrepreneur))}</td>
                  </tr>
                  <tr class="total-row">
                    <td>Total</td>
                    <td class="amount">—</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(totalCa))}</td>
                    <td class="amount">${escapeHtml(
                      formatDzdAmount(
                        Number(declaration.ca_marchandises_imposable || 0) +
                          Number(declaration.ca_services_imposable || 0) +
                          Number(declaration.ca_auto_entrepreneur_imposable || 0),
                      ),
                    )}</td>
                    <td class="amount">${escapeHtml(
                      formatDzdAmount(
                        Number(declaration.ca_marchandises_exonere || 0) +
                          Number(declaration.ca_services_exonere || 0),
                      ),
                    )}</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.ifu_total_ca))}</td>
                  </tr>
                </tbody>
              </table>
            </section>

            ${
              declaration.is_marge_reglementee
                ? `
                  <section class="section">
                    <div class="section-title">
                      <h2>Section III - Marge beneficiaire</h2>
                      <span class="arabic">القسم الثالث - هامش الربح</span>
                    </div>
                    <table>
                      <thead>
                        <tr>
                          <th>Nature</th>
                          <th>Taux</th>
                          <th>CA Global</th>
                          <th>CA Imposable</th>
                          <th>CA Exonere</th>
                          <th>Marge imposable</th>
                          <th>IFU du (B)</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td>Produits a prix / marges reglementes</td>
                          <td class="amount">5,00%</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_marge_global))}</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_marge_imposable))}</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_marge_exonere))}</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.marge_imposable))}</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.ifu_marge))}</td>
                        </tr>
                      </tbody>
                    </table>
                  </section>
                `
                : ""
            }

            <section class="section">
              <div class="section-title">
                <h2>IFU a payer</h2>
                <span class="arabic">الضريبة المستحقة للدفع</span>
              </div>
              <div class="summary-grid">
                <div class="summary-box">
                  <span class="label">IFU calcule sur CA (A)</span>
                  <span class="value">${escapeHtml(formatDzdAmount(declaration.ifu_total_ca))}</span>
                </div>
                <div class="summary-box">
                  <span class="label">IFU calcule sur marge (B)</span>
                  <span class="value">${escapeHtml(formatDzdAmount(declaration.ifu_total_marge))}</span>
                </div>
                <div class="summary-box accent">
                  <span class="label">IFU total a payer</span>
                  <span class="value">${escapeHtml(formatDzdAmount(declaration.total_ifu_du))}</span>
                </div>
                <div class="summary-box ${minimumApplies ? "warning" : "accent"}">
                  <span class="label">Montant effectif a payer</span>
                  <span class="value">${escapeHtml(formatDzdAmount(declaration.montant_effectif_a_payer))}</span>
                </div>
              </div>
              <div class="notice">
                Minimum d'imposition retenu: ${escapeHtml(formatDzdAmount(declaration.minimum_imposition))}.
                ${minimumApplies ? "Le minimum d'imposition est applique pour cette declaration." : "Le calcul IFU depasse le minimum d'imposition."}
              </div>
            </section>

            <section class="section">
              <div class="section-title">
                <h2>Volet paiement</h2>
                <span class="arabic">قسم الدفع</span>
              </div>
              <div class="payment-grid">
                <div class="payment-card ${declaration.mode_paiement === "integral" ? "active" : ""}">
                  <h3>Paiement integral</h3>
                  <ul class="payment-list">
                    <li>Montant: <strong class="amount">${escapeHtml(formatDzdAmount(declaration.paiement_integral_montant))}</strong></li>
                    <li>Quittance: <strong>${escapeHtml(declaration.paiement_integral_quittance || "—")}</strong></li>
                    <li>Date: <strong>${escapeHtml(formatDate(declaration.paiement_integral_date))}</strong></li>
                  </ul>
                </div>
                <div class="payment-card ${declaration.mode_paiement === "fractionne" ? "active" : ""}">
                  <h3>Paiement fractionne</h3>
                  <ul class="payment-list">
                    <li>1re tranche: <strong class="amount">${escapeHtml(formatDzdAmount(declaration.tranche1_montant))}</strong> · ${escapeHtml(formatDate(declaration.tranche1_date))}</li>
                    <li>2e tranche: <strong class="amount">${escapeHtml(formatDzdAmount(declaration.tranche2_montant))}</strong> · ${escapeHtml(formatDate(declaration.tranche2_date))}</li>
                    <li>3e tranche: <strong class="amount">${escapeHtml(formatDzdAmount(declaration.tranche3_montant))}</strong> · ${escapeHtml(formatDate(declaration.tranche3_date))}</li>
                  </ul>
                </div>
                <div class="payment-card ${declaration.mode_paiement === "minimum" ? "active" : ""}">
                  <h3>Mode retenu</h3>
                  <ul class="payment-list">
                    <li><strong>${escapeHtml(paymentModeLabel)}</strong></li>
                    <li>IFU effectif: <strong class="amount">${escapeHtml(formatDzdAmount(declaration.montant_effectif_a_payer))}</strong></li>
                    <li>Date depot: <strong>${escapeHtml(formatDate(declaration.date_depot))}</strong></li>
                    <li>Statut: <strong>${escapeHtml(declaration.statut_label || declaration.statut)}</strong></li>
                  </ul>
                </div>
              </div>
              <div class="notice">
                (*) Le paiement fractionne est reserve aux declarations deposees dans les delais de l'art. 365 CIDTA.
              </div>
            </section>

            <section class="section">
              <div class="section-title">
                <h2>Certification</h2>
                <span class="arabic">التصديق</span>
              </div>
              <p>
                J'atteste de l'exactitude des renseignements portes sur la presente declaration.
              </p>
              <div class="signature-grid">
                <div class="signature-box">
                  <span class="info-label">Lieu</span>
                  <div class="info-value">${escapeHtml(declaration.lieu_declaration || company.city || "—")}</div>
                </div>
                <div class="signature-box">
                  <span class="info-label">Date</span>
                  <div class="info-value">${escapeHtml(formatDate(declaration.date_signature || declaration.date_depot))}</div>
                </div>
              </div>
              <p class="footer-note">
                Document genere le ${escapeHtml(formatDate(new Date().toISOString()))} par ${escapeHtml(generatedBy)}.
              </p>
            </section>
          </div>
        </div>
      </body>
    </html>
  `;
};

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

  try {
    const page = await browser.newPage();
    await page.setContent(
      buildHtml({
        company,
        profile,
        declaration,
        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;">GN°12 Prévisionnelle IFU</span>
            <span>${escapeHtml(company.name || "Société")}</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 généré par ${escapeHtml(generatedBy || "Système")}</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();
  }
};
