# apps/wp_invoices_mail_app/email_templates.py
from __future__ import annotations
from typing import List, Dict, Any

from shared.branding.branding import get_mail_theme


def _esc(s: str) -> str:
    return (
        str(s)
        .replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
    )


def render_results_email_html(results: List[Dict[str, Any]]) -> str:
    """
    Renderiza el correo HTML con branding para el resumen de facturas.
    (Versión en inglés; el texto plano sigue en español para compatibilidad).
    """
    theme = get_mail_theme()

    font_stack      = theme["font_stack"]
    page_bg         = theme["page_bg"]
    card_bg         = theme["card_bg"]
    border_color    = theme["border_color"]
    brand_color     = theme["brand_color"]
    text_color      = theme["text_color"]
    secondary_text  = theme["secondary_text"]
    success_color   = theme["success_color"]
    error_color     = theme["error_color"]
    stat_bg         = theme["stat_bg"]
    table_header_bg = theme["table_header_bg"]
    tag_bg          = theme["tag_bg"]
    tag_text        = theme["tag_text"]

    total = len(results)
    n_ok = sum(1 for r in results if r.get("ok", True) and not r.get("error"))
    n_err = total - n_ok

    # Intro
    if not results:
        intro_html = """
        <p>We received your email but could not process any valid invoice.</p>
        <p>Please make sure the attachments are clear invoice images or PDF files.</p>
        """
    else:
        if total == 1:
            intro_html = "<p>We processed the attached invoice and here is the result:</p>"
        else:
            intro_html = f"<p>We processed <strong>{total}</strong> attached invoices. Summary below:</p>"

    # Filas por factura
    rows_html: list[str] = []

    for idx, r in enumerate(results, start=1):
        fname = r.get("filename") or r.get("original_filename") or "(no filename)"
        ok_flag = r.get("ok", True)
        error_msg = r.get("error")

        if not ok_flag or error_msg:
            status_label = "Not processed"
            details = error_msg or "Unknown error."
        else:
            extracted = r.get("extracted") or {}
            header = extracted.get("header", {})
            supplier = header.get("supplier", {})
            invoice_block = header.get("invoice", {}) or {}
            totals = extracted.get("totals", {}) or {}

            def pick(node: Any) -> str:
                if isinstance(node, dict):
                    return node.get("verbatim") or node.get("computed") or ""
                return node or ""

            supplier_name = pick(supplier.get("name"))
            invoice_number = pick(invoice_block.get("number"))
            issue_date = pick((invoice_block.get("date") or {}).get("issue_date"))
            grand_total = pick(totals.get("grand_total"))
            currency = totals.get("currency") or "AUD"

            parts = []
            if supplier_name:
                parts.append(f"Supplier: <strong>{_esc(supplier_name)}</strong>")
            if invoice_number:
                parts.append(f"Invoice #: {_esc(invoice_number)}")
            if issue_date:
                parts.append(f"Date: {_esc(issue_date)}")
            if grand_total:
                parts.append(f"Total: {_esc(grand_total)} {_esc(currency)}")

            status_label = "Processed"
            details = "<br>".join(parts) if parts else "Extracted successfully."

        rows_html.append(
            f"""
            <tr>
              <td>{idx}</td>
              <td>{_esc(fname)}</td>
              <td>{status_label}</td>
              <td>{details}</td>
            </tr>
            """
        )

    rows_block = "\n".join(rows_html)

    # HTML completo (wireframe opción B)
    html = f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Invoice Bot – Processing summary</title>
  <style>
    body {{
      margin: 0;
      padding: 0;
      background: {page_bg};
      font-family: {font_stack};
      color: {text_color};
    }}
    .wrapper {{
      max-width: 640px;
      margin: 0 auto;
      padding: 24px 12px;
    }}
    .card {{
      background: {card_bg};
      border-radius: 12px;
      border: 1px solid {border_color};
      padding: 22px 20px;
      box-sizing: border-box;
    }}
    .brand-header {{
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      margin-bottom: 16px;
    }}
    .brand-title {{
      font-size: 18px;
      font-weight: 600;
      color: {brand_color};
    }}
    .tag {{
      font-size: 11px;
      text-transform: uppercase;
      letter-spacing: 0.04em;
      padding: 4px 8px;
      border-radius: 999px;
      background: {tag_bg};
      color: {tag_text};
    }}
    .intro {{
      font-size: 14px;
      margin-bottom: 14px;
    }}
    .stats-row {{
      display: flex;
      gap: 12px;
      margin: 10px 0 18px 0;
      flex-wrap: wrap;
    }}
    .stat-box {{
      flex: 1 1 120px;
      border-radius: 10px;
      background: {stat_bg};
      padding: 10px 12px;
      box-sizing: border-box;
    }}
    .stat-label {{
      font-size: 11px;
      color: {secondary_text};
      margin-bottom: 4px;
      text-transform: uppercase;
      letter-spacing: 0.04em;
    }}
    .stat-value {{
      font-size: 18px;
      font-weight: 600;
    }}
    .stat-ok {{
      color: {success_color};
    }}
    .stat-err {{
      color: {error_color};
    }}
    .details-title {{
      font-size: 13px;
      font-weight: 600;
      margin-bottom: 6px;
    }}
    table.details-table {{
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 12px;
    }}
    .details-table th,
    .details-table td {{
      font-size: 12px;
      padding: 6px 8px;
      border-bottom: 1px solid {border_color};
      text-align: left;
      vertical-align: top;
    }}
    .details-table th {{
      background: {table_header_bg};
      font-weight: 600;
    }}
    .footer-note {{
      margin-top: 12px;
      font-size: 11px;
      color: {secondary_text};
    }}
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="card">
      <div class="brand-header">
        <div class="brand-title">Invoice Bot – Absolutems</div>
        <div class="tag">Summary</div>
      </div>

      <div class="intro">
        {intro_html}
      </div>

      {"" if not results else f"""
      <div class="stats-row">
        <div class="stat-box">
          <div class="stat-label">Processed OK</div>
          <div class="stat-value stat-ok">{n_ok}</div>
        </div>
        <div class="stat-box">
          <div class="stat-label">With errors</div>
          <div class="stat-value stat-err">{n_err}</div>
        </div>
      </div>

      <div class="details-title">Per-invoice details</div>
      <table class="details-table">
        <thead>
          <tr>
            <th>#</th>
            <th>File</th>
            <th>Status</th>
            <th>Details</th>
          </tr>
        </thead>
        <tbody>
          {rows_block}
        </tbody>
      </table>
      """}

      <div class="footer-note">
        If something looks wrong, please double-check the original supplier invoice.
        The system may have doubts in low-quality or partially readable areas.
        <br/><br/>
        Review PDFs are attached for every invoice processed successfully.
        Invoices marked as “Not processed” will not have a review PDF.
      </div>
    </div>
  </div>
</body>
</html>
"""
    return html
