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 buildHtml = ({ company, profile, declaration, yearItems, generatedBy }) => `
  <!DOCTYPE html>
  <html lang="fr">
    <head>
      <meta charset="utf-8" />
      <title>G50ter ${escapeHtml(declaration.annee)} T${escapeHtml(declaration.trimestre)}</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;
        }
        .topline, .section-title {
          display: flex;
          justify-content: space-between;
          gap: 16px;
          align-items: baseline;
        }
        .small {
          font-size: 10px;
          color: #475569;
          text-transform: uppercase;
          letter-spacing: 0.12em;
          margin: 0;
        }
        .title {
          margin: 12px 0 0;
          color: #1d4ed8;
          font-size: 18px;
          font-weight: 800;
          text-transform: uppercase;
        }
        .subtitle {
          margin: 6px 0 0;
          color: #475569;
          font-size: 11px;
        }
        .arabic {
          direction: rtl;
          font-family: Tahoma, Arial, sans-serif;
        }
        .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 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: #fff;
        }
        .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; }
        table {
          width: 100%;
          border-collapse: collapse;
        }
        th, td {
          border: 1px solid #cbd5e1;
          padding: 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;
        }
        .active-row td {
          background: #eff6ff;
          font-weight: 700;
        }
        .signature-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 14px;
        }
      </style>
    </head>
    <body>
      <div class="page">
        <div class="sheet">
          <div class="sheet-header">
            <div class="topline">
              <div>
                <p class="small">Direction des Impots de Wilaya</p>
                <p><strong>${escapeHtml(company.city || "—")}</strong></p>
              </div>
              <div style="text-align:right;">
                <p class="small arabic">مديرية الضرائب للولاية</p>
                <p><strong class="arabic">الضريبة الجزافية الوحيدة - الأجور</strong></p>
              </div>
            </div>
            <div style="display:grid;grid-template-columns:1fr auto;gap:16px;align-items:end;margin-top:16px;">
              <div>
                <h1 class="title">Impot Forfaitaire Unique - IRG / Salaires - Serie G50ter</h1>
                <p class="subtitle">
                  Declaration trimestrielle ${escapeHtml(declaration.quarter_label)} · ${escapeHtml(declaration.periode_label)}
                </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>Identification</h2>
              <span class="arabic">التعريف</span>
            </div>
            <div class="info-grid">
              <div class="info-box">
                <span class="info-label">NIF / NIN / Article</span>
                <div class="info-value">
                  NIF ${escapeHtml(declaration.nif || company.nif || "—")} ·
                  NIN ${escapeHtml(declaration.nin || profile?.nin || "—")} ·
                  AI ${escapeHtml(declaration.article_imposition || profile?.article_imposition || company.ai || "—")}
                </div>
              </div>
              <div class="info-box">
                <span class="info-label">Code activite</span>
                <div class="info-value">${escapeHtml(declaration.code_activite || profile?.code_activite || "—")}</div>
              </div>
              <div class="info-box">
                <span class="info-label">Nom / Raison sociale</span>
                <div class="info-value">${escapeHtml(company.name || "—")}</div>
              </div>
              <div class="info-box">
                <span class="info-label">Activite</span>
                <div class="info-value">${escapeHtml(profile?.activity_description || "—")}</div>
              </div>
              <div class="info-box full">
                <span class="info-label">Adresse</span>
                <div class="info-value">${escapeHtml(company.address || "—")}</div>
              </div>
            </div>
          </section>

          <section class="section">
            <div class="section-title">
              <h2>Tableau trimestriel</h2>
              <span class="arabic">الجدول الفصلي</span>
            </div>
            <table>
              <thead>
                <tr>
                  <th>Trimestre</th>
                  <th>Mois concernes</th>
                  <th>Salaires imposables</th>
                  <th>Taux</th>
                  <th>Montant IRG</th>
                  <th>Delai</th>
                  <th>Statut</th>
                </tr>
              </thead>
              <tbody>
                ${yearItems
                  .map(
                    (item) => `
                      <tr class="${item.id === declaration.id ? "active-row" : ""}">
                        <td>${escapeHtml(item.quarter_label)}</td>
                        <td>${escapeHtml(item.months_label)}</td>
                        <td class="amount">${escapeHtml(formatDzdAmount(item.salaires_imposables_t))}</td>
                        <td>${escapeHtml(item.taux_bareme || "Bareme IRG")}</td>
                        <td class="amount">${escapeHtml(formatDzdAmount(item.montant_irg))}</td>
                        <td>${escapeHtml(item.deadline_label)}</td>
                        <td>${escapeHtml(item.statut_label || item.statut)}</td>
                      </tr>
                    `,
                  )
                  .join("")}
              </tbody>
            </table>
          </section>

          <section class="section">
            <div class="section-title">
              <h2>Paiement</h2>
              <span class="arabic">الدفع</span>
            </div>
            <table>
              <thead>
                <tr>
                  <th>Quittance</th>
                  <th>Date quittance</th>
                  <th>Date versement</th>
                  <th>Montant IRG</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>${escapeHtml(declaration.quittance_numero || "—")}</td>
                  <td>${escapeHtml(formatDate(declaration.quittance_date))}</td>
                  <td>${escapeHtml(formatDate(declaration.date_versement))}</td>
                  <td class="amount">${escapeHtml(formatDzdAmount(declaration.montant_irg))}</td>
                </tr>
              </tbody>
            </table>
          </section>

          <section class="section">
            <div class="section-title">
              <h2>Signatures</h2>
              <span class="arabic">التوقيعات</span>
            </div>
            <div class="signature-grid">
              <div class="info-box">
                <span class="info-label">Contribuable</span>
                <div class="info-value">
                  Lieu: ${escapeHtml(declaration.lieu_declaration || company.city || "—")}<br />
                  Date: ${escapeHtml(formatDate(declaration.date_signature))}<br />
                  Cachet et signature du contribuable
                </div>
              </div>
              <div class="info-box">
                <span class="info-label">Receveur</span>
                <div class="info-value">
                  ${escapeHtml(declaration.receveur_signature || "—")}<br />
                  ${escapeHtml(formatDate(declaration.receveur_date))}
                </div>
              </div>
            </div>
            <p class="subtitle" style="margin-top:12px;">
              Document genere le ${escapeHtml(formatDate(new Date().toISOString()))} par ${escapeHtml(generatedBy)}.
            </p>
          </section>
        </div>
      </div>
    </body>
  </html>
`;

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

  try {
    const page = await browser.newPage();
    await page.setContent(
      buildHtml({
        company,
        profile,
        declaration,
        yearItems,
        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;">G50ter IFU</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();
  }
};
