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 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 renderComparisonRow = ({
  label,
  rate,
  realImposable,
  realExonere,
  realGlobal,
  prevImposable,
  prevGlobal,
  complementaire,
  ifuComplementaire,
}) => `
  <tr>
    <td>${escapeHtml(label)}</td>
    <td class="amount">${escapeHtml(formatDzdAmount(realImposable))}</td>
    <td class="amount">${escapeHtml(formatDzdAmount(realExonere))}</td>
    <td class="amount">${escapeHtml(formatDzdAmount(realGlobal))}</td>
    <td class="amount">${escapeHtml(formatDzdAmount(prevImposable))}</td>
    <td class="amount">${escapeHtml(formatDzdAmount(prevGlobal))}</td>
    <td class="amount ${Number(complementaire || 0) >= 0 ? "is-up" : "is-down"}">
      ${escapeHtml(formatDzdAmount(complementaire))}
    </td>
    <td class="amount">${escapeHtml(formatDzdAmount(ifuComplementaire))}</td>
    <td class="amount">${escapeHtml(`${Number(rate || 0).toFixed(2).replace(".", ",")}%`)}</td>
  </tr>
`;

const buildHtml = ({ company, profile, declaration, generatedBy }) => {
  const exonerationFlags = new Set(declaration.exoneration_flags || []);
  const minimumApplies =
    Number(declaration.minimum_gap_due || 0) > 0.009 ||
    Number(declaration.total_ifu_exercice || 0) <= Number(declaration.minimum_imposition || 0) + 0.009;

  return `
    <!DOCTYPE html>
    <html lang="fr">
      <head>
        <meta charset="utf-8" />
        <title>GN12 Bis ${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.12), rgba(255,255,255,0.94)),
              #f8fafc;
            border-bottom: 1px solid #cbd5e1;
          }
          .topline {
            display: flex;
            justify-content: space-between;
            gap: 16px;
            align-items: flex-start;
          }
          .topline p { margin: 0; }
          .small {
            font-size: 10px;
            color: #475569;
            text-transform: uppercase;
            letter-spacing: 0.12em;
          }
          .arabic {
            direction: rtl;
            font-family: Tahoma, Arial, sans-serif;
          }
          .title-grid {
            display: grid;
            grid-template-columns: 1fr auto;
            gap: 16px;
            margin-top: 16px;
            align-items: end;
          }
          .title {
            margin: 0;
            color: #1d4ed8;
            font-size: 18px;
            font-weight: 800;
            text-transform: uppercase;
          }
          .subtitle {
            margin: 6px 0 0;
            color: #475569;
            font-size: 11px;
          }
          .badge {
            padding: 10px 14px;
            border-radius: 14px;
            border: 1px solid #bfdbfe;
            background: #eff6ff;
            text-align: right;
          }
          .badge strong {
            display: block;
            color: #1d4ed8;
            font-size: 18px;
          }
          .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;
          }
          .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;
            gap: 8px;
            align-items: center;
          }
          .checkbox-box {
            width: 16px;
            height: 16px;
            border: 1px solid #64748b;
            border-radius: 4px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: #1d4ed8;
            background: #ffffff;
            font-size: 12px;
          }
          .checkbox-box.checked {
            border-color: #1d4ed8;
            background: #eff6ff;
          }
          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;
            font-family: "JetBrains Mono", "Courier New", monospace;
            white-space: nowrap;
          }
          .is-up { color: #dc2626; }
          .is-down { color: #059669; }
          .summary-grid {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 12px;
          }
          .summary-box {
            border: 1px solid #cbd5e1;
            border-radius: 14px;
            background: #f8fafc;
            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;
            font-size: 10px;
            letter-spacing: 0.08em;
            text-transform: uppercase;
          }
          .summary-box .value {
            display: block;
            margin-top: 8px;
            font-size: 16px;
            font-weight: 800;
            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;
          }
        </style>
      </head>
      <body>
        <div class="page">
          <div class="sheet">
            <div class="sheet-header">
              <div class="topline">
                <div>
                  <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 style="text-align:right;">
                  <p class="small">الجمهورية الجزائرية الديمقراطية الشعبية</p>
                  <p><strong class="arabic">التصريح النهائي لنظام الضريبة الجزافية الوحيدة</strong></p>
                </div>
              </div>
              <div class="title-grid">
                <div>
                  <h1 class="title">Declaration Definitive - Regime IFU - Serie GN 12 Bis (${escapeHtml(
                    declaration.annee,
                  )})</h1>
                  <p class="subtitle">
                    Periode du ${escapeHtml(formatDate(declaration.periode_du))} au ${escapeHtml(
                      formatDate(declaration.periode_au),
                    )}
                  </p>
                </div>
                <div class="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 || profile?.activity_description || "—")}</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">Telephone</span>
                  <div class="info-value">${escapeHtml(declaration.telephone || company.phone || "—")}</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">
                  <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">
                  <span class="info-label">Nouveau contribuable</span>
                  <div>${renderCheckbox(Boolean(declaration.is_nouveau_contribuable), "Oui", "نعم")}</div>
                </div>
                <div class="info-box full">
                  <span class="info-label">Activite exoneree</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 - Volet salaires</h2>
                <span class="arabic">القسم الثاني - الأجور</span>
              </div>
              <table>
                <thead>
                  <tr>
                    <th>Nombre de salaries</th>
                    <th>Total brut verse</th>
                    <th>Charges sociales</th>
                    <th>IRG / Salaires acquitte</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td class="amount">${escapeHtml(String(declaration.nb_salaries || 0))}</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.total_salaires_bruts))}</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.total_charges_sociales))}</td>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.total_irg_salaires_acquitte))}</td>
                  </tr>
                </tbody>
              </table>
            </section>

            <section class="section">
              <div class="section-title">
                <h2>Section III - CA / Recettes definitifs</h2>
                <span class="arabic">القسم الثالث - رقم الأعمال النهائي</span>
              </div>
              <table>
                <thead>
                  <tr>
                    <th>Nature d'activite</th>
                    <th>Reel imposable</th>
                    <th>Reel exonere</th>
                    <th>Reel global</th>
                    <th>Prev imposable</th>
                    <th>Prev global</th>
                    <th>Complementaire</th>
                    <th>IFU compl.</th>
                    <th>Taux</th>
                  </tr>
                </thead>
                <tbody>
                  ${renderComparisonRow({
                    label: "Production / Vente de marchandises",
                    rate: 5,
                    realImposable: declaration.ca_marchandises_reel_imposable,
                    realExonere: declaration.ca_marchandises_reel_exonere,
                    realGlobal: declaration.ca_marchandises_reel_global,
                    prevImposable: declaration.ca_marchandises_prev_imposable,
                    prevGlobal: declaration.ca_marchandises_prev_global,
                    complementaire: declaration.ca_marchandises_complementaire,
                    ifuComplementaire: declaration.ifu_complementaire_marchandises,
                  })}
                  ${renderComparisonRow({
                    label: "Prestations de services / Autres activites",
                    rate: 12,
                    realImposable: declaration.ca_services_reel_imposable,
                    realExonere: declaration.ca_services_reel_exonere,
                    realGlobal: declaration.ca_services_reel_global,
                    prevImposable: declaration.ca_services_prev_imposable,
                    prevGlobal: declaration.ca_services_prev_global,
                    complementaire: declaration.ca_services_complementaire,
                    ifuComplementaire: declaration.ifu_complementaire_services,
                  })}
                  ${renderComparisonRow({
                    label: "Activites auto-entrepreneur",
                    rate: 0.5,
                    realImposable: declaration.ca_ae_reel_imposable,
                    realExonere: declaration.ca_ae_reel_exonere,
                    realGlobal: declaration.ca_ae_reel_global,
                    prevImposable: declaration.ca_ae_prev_imposable,
                    prevGlobal: declaration.ca_ae_prev_global,
                    complementaire: declaration.ca_ae_complementaire,
                    ifuComplementaire: declaration.ifu_complementaire_ae,
                  })}
                </tbody>
              </table>
            </section>

            ${
              declaration.is_marge_reglementee
                ? `
                  <section class="section">
                    <div class="section-title">
                      <h2>Section IV - Marge beneficiaire</h2>
                      <span class="arabic">القسم الرابع - هامش الربح</span>
                    </div>
                    <table>
                      <thead>
                        <tr>
                          <th>CA reel imposable</th>
                          <th>CA reel exonere</th>
                          <th>CA reel global</th>
                          <th>CA prev imposable</th>
                          <th>CA prev global</th>
                          <th>Marge realisee</th>
                          <th>Marge prev.</th>
                          <th>Compl.</th>
                          <th>IFU compl.</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_marge_reel_imposable))}</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_marge_reel_exonere))}</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_marge_reel_global))}</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_marge_prev_imposable))}</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.ca_marge_prev_global))}</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.marge_realisee))}</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.marge_previsionnelle))}</td>
                          <td class="amount ${Number(declaration.marge_complementaire || 0) >= 0 ? "is-up" : "is-down"}">${escapeHtml(formatDzdAmount(declaration.marge_complementaire))}</td>
                          <td class="amount">${escapeHtml(formatDzdAmount(declaration.ifu_complementaire_marge))}</td>
                        </tr>
                      </tbody>
                    </table>
                  </section>
                `
                : ""
            }

            <section class="section">
              <div class="section-title">
                <h2>IFU complementaire a payer</h2>
                <span class="arabic">الضريبة التكميلية المستحقة</span>
              </div>
              <div class="summary-grid">
                <div class="summary-box">
                  <span class="label">IFU previsionnel acquitte</span>
                  <span class="value">${escapeHtml(formatDzdAmount(declaration.ifu_previsionnel_acquitte))}</span>
                </div>
                <div class="summary-box accent">
                  <span class="label">IFU complementaire du</span>
                  <span class="value">${escapeHtml(formatDzdAmount(declaration.total_ifu_complementaire))}</span>
                </div>
                <div class="summary-box accent">
                  <span class="label">Total IFU exercice</span>
                  <span class="value">${escapeHtml(formatDzdAmount(declaration.total_ifu_exercice))}</span>
                </div>
                <div class="summary-box ${minimumApplies ? "warning" : "accent"}">
                  <span class="label">Minimum d'imposition</span>
                  <span class="value">${escapeHtml(formatDzdAmount(declaration.minimum_imposition))}</span>
                </div>
              </div>
              <div class="notice">
                Revenu net declare: ${escapeHtml(formatDzdAmount(declaration.revenu_net_declare))}.
                ${
                  Number(declaration.minimum_gap_due || 0) > 0.009
                    ? ` Le minimum d'imposition majore l'IFU complémentaire de ${escapeHtml(
                        formatDzdAmount(declaration.minimum_gap_due),
                      )}.`
                    : ""
                }
              </div>
            </section>

            <section class="section">
              <div class="section-title">
                <h2>Volet paiement</h2>
                <span class="arabic">قسم الدفع</span>
              </div>
              <table>
                <thead>
                  <tr>
                    <th>Montant acquitte</th>
                    <th>Quittance</th>
                    <th>Date</th>
                    <th>Statut</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td class="amount">${escapeHtml(formatDzdAmount(declaration.montant_acquitte))}</td>
                    <td>${escapeHtml(declaration.quittance_numero || "—")}</td>
                    <td>${escapeHtml(formatDate(declaration.quittance_date))}</td>
                    <td>${escapeHtml(declaration.statut_label || declaration.statut)}</td>
                  </tr>
                </tbody>
              </table>
            </section>

            <section class="section">
              <div class="section-title">
                <h2>Certification</h2>
                <span class="arabic">التصديق</span>
              </div>
              <p>J'atteste de l'exactitude des renseignements portés sur la présente déclaration.</p>
              <div class="info-grid">
                <div class="info-box">
                  <span class="info-label">Lieu</span>
                  <div class="info-value">${escapeHtml(declaration.lieu_declaration || company.city || "—")}</div>
                </div>
                <div class="info-box">
                  <span class="info-label">Date</span>
                  <div class="info-value">${escapeHtml(formatDate(declaration.date_signature || declaration.date_depot))}</div>
                </div>
              </div>
              <p class="subtitle" style="margin-top:12px;">
                Document généré le ${escapeHtml(formatDate(new Date().toISOString()))} par ${escapeHtml(generatedBy)}.
              </p>
            </section>
          </div>
        </div>
      </body>
    </html>
  `;
};

export const buildGn12BisPdfBuffer = 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 Bis Définitive 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();
  }
};
