"""Transactional email service.

Priority:
1. If SMTP settings are configured in the admin Settings panel → use SMTP (hosting email).
2. Else if RESEND_API_KEY env var is set → use Resend.
3. Else → log + skip (no error raised).

All sends are logged to `email_logs` collection regardless of provider.
"""
import os
import asyncio
import logging
import uuid
import smtplib
import ssl
from email.message import EmailMessage
from datetime import datetime, timezone
from typing import Optional
import resend

from db import get_db
from bd_time import now_bd_str, fmt_bd_long

logger = logging.getLogger(__name__)

RESEND_API_KEY = os.environ.get("RESEND_API_KEY", "")
DEFAULT_SENDER = os.environ.get("SENDER_EMAIL", "onboarding@resend.dev")

if RESEND_API_KEY:
    resend.api_key = RESEND_API_KEY


async def _get_email_settings() -> dict:
    """Read live SMTP + Resend settings.

    Priority for each SMTP field:
      1. DB `settings` document (admin panel controlled)
      2. Environment variable fallback (for cPanel / fresh-deploy scenarios
         where DB may not be seeded yet)
    Falls back to empty values if neither is set.
    """
    db = get_db()
    doc = await db.settings.find_one({"id": "global"}, {"_id": 0}) or {}

    def pick(db_key: str, env_key: str, default=None):
        v = doc.get(db_key)
        if v not in (None, ""):
            return v
        return os.environ.get(env_key, default)

    return {
        **doc,
        "smtp_host": pick("smtp_host", "SMTP_HOST", ""),
        "smtp_port": int(pick("smtp_port", "SMTP_PORT", 465) or 465),
        "smtp_user": pick("smtp_user", "SMTP_USER", ""),
        "smtp_password": pick("smtp_password", "SMTP_PASSWORD", ""),
        "smtp_from_name": pick("smtp_from_name", "SMTP_FROM_NAME", "Maxlife88 Agent Portal"),
        "smtp_use_ssl": doc.get("smtp_use_ssl") if doc.get("smtp_use_ssl") is not None
                        else (os.environ.get("SMTP_USE_SSL", "true").lower() != "false"),
        "sender_email": pick("sender_email", "SENDER_EMAIL", DEFAULT_SENDER),
        "notification_email": pick("notification_email", "ADMIN_EMAIL", ""),
    }


async def _log_email(
    to: str,
    subject: str,
    email_type: str,
    status: str,
    provider: str = "skipped",
    resend_id: Optional[str] = None,
    error: Optional[str] = None,
    application_id: Optional[str] = None,
    sender: Optional[str] = None,
):
    try:
        db = get_db()
        await db.email_logs.insert_one({
            "id": str(uuid.uuid4()),
            "to": to,
            "subject": subject,
            "email_type": email_type,
            "status": status,
            "provider": provider,
            "resend_id": resend_id,
            "error": error,
            "application_id": application_id,
            "sender": sender or DEFAULT_SENDER,
            "sent_at": datetime.now(timezone.utc).isoformat(),
        })
    except Exception as e:
        logger.error("Could not write email log: %s", e)


def _wrap_html(title: str, body_html: str, accent: str = "#10B981", preheader: str = "") -> str:
    """Premium email wrapper — gradient header, hero badge, polished footer.

    `preheader` shows as the email preview text in inboxes (hidden in body).
    """
    return f"""\
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>{title}</title>
</head>
<body style="margin:0;padding:0;background:#0a1119;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#cbd5e1;">
  <!-- Preheader (hidden but shown in inbox preview) -->
  <div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;mso-hide:all;">
    {preheader or title}
  </div>

  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
         style="background:#0a1119;padding:32px 12px;">
    <tr><td align="center">
      <table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0"
             style="max-width:600px;width:100%;background:#0F1A28;border-radius:18px;overflow:hidden;
                    border:1px solid rgba(16,185,129,0.18);box-shadow:0 30px 60px rgba(0,0,0,0.35);">

        <!-- Gradient header band -->
        <tr><td style="background:linear-gradient(135deg,#062d22 0%,#0a1119 60%,{accent} 220%);
                       padding:34px 36px;border-bottom:1px solid rgba(16,185,129,0.16);">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
            <tr>
              <td style="font-size:13px;font-weight:700;color:{accent};letter-spacing:1.8px;
                         text-transform:uppercase;font-family:'Segoe UI',Roboto,sans-serif;">
                ● Maxlife88 Agent Portal
              </td>
              <td align="right" style="font-size:11px;color:#64748b;font-family:Menlo,Consolas,monospace;">
                {now_bd_str("%d %b %Y · %I:%M %p")} BDT
              </td>
            </tr>
          </table>
        </td></tr>

        <!-- Hero title -->
        <tr><td style="padding:36px 36px 8px 36px;">
          <h1 style="margin:0 0 6px 0;color:#ffffff;font-size:26px;font-weight:700;
                     line-height:1.25;letter-spacing:-0.4px;font-family:'Segoe UI',Roboto,sans-serif;">
            {title}
          </h1>
          <div style="display:inline-block;height:3px;width:48px;background:{accent};border-radius:2px;margin-top:4px;"></div>
        </td></tr>

        <!-- Body -->
        <tr><td style="padding:18px 36px 32px 36px;color:#cbd5e1;font-size:15px;line-height:1.75;">
          {body_html}
        </td></tr>

        <!-- Footer -->
        <tr><td style="padding:22px 36px;border-top:1px solid rgba(255,255,255,0.06);
                       background:#0a1119;">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
            <tr>
              <td style="color:#64748b;font-size:11px;line-height:1.6;">
                Automated message from <strong style="color:#94a3b8;">Maxlife88 Agent Portal</strong> ·
                Please do not reply.<br/>
                <span style="color:#475569;">এটি একটি স্বয়ংক্রিয় বার্তা — অনুগ্রহ করে এই ইমেইলে রিপ্লাই করবেন না।</span>
              </td>
            </tr>
          </table>
        </td></tr>
      </table>

      <!-- Bottom brand line -->
      <table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;width:100%;">
        <tr><td align="center" style="padding:14px 12px 0 12px;color:#475569;font-size:11px;font-family:'Segoe UI',Roboto,sans-serif;">
          © Maxlife88 · Bangladesh's most trusted agent network
        </td></tr>
      </table>

    </td></tr>
  </table>
</body></html>
"""


def _send_smtp_sync(
    smtp_host: str,
    smtp_port: int,
    smtp_user: str,
    smtp_password: str,
    smtp_use_ssl: bool,
    from_addr: str,
    from_name: str,
    to: str,
    subject: str,
    html: str,
    attachments: Optional[list] = None,
) -> None:
    """Blocking SMTP send. Should be called via asyncio.to_thread.

    attachments: list of dicts: {"filename": str, "content": bytes, "mime_type": "application/pdf"}
    """
    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = f"{from_name} <{from_addr}>" if from_name else from_addr
    msg["To"] = to
    # Plain-text fallback then HTML alternative
    msg.set_content("This email requires an HTML-capable client.")
    msg.add_alternative(html, subtype="html")

    if attachments:
        for att in attachments:
            mime = att.get("mime_type", "application/octet-stream")
            maintype, _, subtype = mime.partition("/")
            msg.add_attachment(
                att["content"],
                maintype=maintype or "application",
                subtype=subtype or "octet-stream",
                filename=att.get("filename", "attachment"),
            )

    if smtp_use_ssl:
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL(smtp_host, smtp_port, context=context, timeout=20) as s:
            s.login(smtp_user, smtp_password)
            s.send_message(msg)
    else:
        with smtplib.SMTP(smtp_host, smtp_port, timeout=20) as s:
            s.ehlo()
            s.starttls(context=ssl.create_default_context())
            s.ehlo()
            s.login(smtp_user, smtp_password)
            s.send_message(msg)


async def send_email(
    to: str,
    subject: str,
    html: str,
    sender: Optional[str] = None,
    email_type: str = "generic",
    application_id: Optional[str] = None,
    attachments: Optional[list] = None,
) -> dict:
    """Send email via SMTP (preferred) or Resend (fallback). Logs every attempt.

    attachments: optional list of {"filename","content"(bytes),"mime_type"}.
    """
    settings = await _get_email_settings()
    smtp_host = (settings.get("smtp_host") or "").strip()
    smtp_user = (settings.get("smtp_user") or "").strip()
    smtp_password = settings.get("smtp_password") or ""

    # ---- SMTP path (preferred) ----
    if smtp_host and smtp_user and smtp_password:
        smtp_port = int(settings.get("smtp_port") or 465)
        smtp_use_ssl = bool(settings.get("smtp_use_ssl", True))
        configured_sender = (sender or settings.get("sender_email") or "").strip()
        # If no sender, or default resend address, OR sender domain doesn't match smtp_user domain,
        # fall back to smtp_user to avoid "Sender address rejected" errors.
        smtp_user_domain = smtp_user.split("@")[-1].lower() if "@" in smtp_user else ""
        sender_domain = configured_sender.split("@")[-1].lower() if "@" in configured_sender else ""
        if (
            not configured_sender
            or "resend.dev" in configured_sender.lower()
            or (smtp_user_domain and sender_domain and smtp_user_domain != sender_domain)
        ):
            from_addr = smtp_user
        else:
            from_addr = configured_sender
        from_name = settings.get("smtp_from_name") or "Maxlife88 Agent Portal"
        try:
            await asyncio.to_thread(
                _send_smtp_sync,
                smtp_host,
                smtp_port,
                smtp_user,
                smtp_password,
                smtp_use_ssl,
                from_addr,
                from_name,
                to,
                subject,
                html,
                attachments,
            )
            logger.info("SMTP email sent to %s via %s:%s (attachments=%d)", to, smtp_host, smtp_port, len(attachments or []))
            await _log_email(to, subject, email_type, "sent", provider="smtp", application_id=application_id, sender=from_addr)
            return {"success": True, "provider": "smtp"}
        except Exception as e:
            err = str(e)[:500]
            logger.error("SMTP send failed to %s: %s", to, err)
            await _log_email(to, subject, email_type, "failed", provider="smtp", error=err, application_id=application_id, sender=from_addr)
            return {"success": False, "provider": "smtp", "error": err}

    # ---- Resend fallback ----
    if RESEND_API_KEY:
        from_addr = sender or settings.get("sender_email") or DEFAULT_SENDER
        params = {"from": from_addr, "to": [to], "subject": subject, "html": html}
        if attachments:
            # Resend accepts base64-encoded content
            import base64
            params["attachments"] = [
                {
                    "filename": a.get("filename", "attachment"),
                    "content": base64.b64encode(a["content"]).decode("ascii"),
                }
                for a in attachments
            ]
        try:
            result = await asyncio.to_thread(resend.Emails.send, params)
            rid = result.get("id")
            logger.info("Resend email sent to %s id=%s", to, rid)
            await _log_email(to, subject, email_type, "sent", provider="resend", resend_id=rid, application_id=application_id, sender=from_addr)
            return {"success": True, "provider": "resend", "id": rid}
        except Exception as e:
            err = str(e)[:500]
            logger.error("Resend send failed to %s: %s", to, err)
            await _log_email(to, subject, email_type, "failed", provider="resend", error=err, application_id=application_id, sender=from_addr)
            return {"success": False, "provider": "resend", "error": err}

    # ---- Nothing configured ----
    logger.warning("No email provider configured. Skipping email to %s", to)
    await _log_email(to, subject, email_type, "skipped", provider="none", error="no_provider_configured", application_id=application_id, sender=sender)
    return {"skipped": True, "reason": "no_provider"}


async def send_test_email(to: str) -> dict:
    """Admin → Settings → Test SMTP button calls this."""
    body = f"""
<p style="color:#e2e8f0;">Hello 👋</p>
<p style="color:#cbd5e1;">This is a <strong style="color:#10B981;">test email</strong> from your Maxlife88 Agent Portal SMTP setup.</p>
<p style="color:#cbd5e1;">If you received this, your hosting SMTP is configured correctly and ready to send transactional emails.</p>
<p style="color:#94a3b8;font-size:13px;">আপনি যদি এই ইমেইলটি পেয়ে থাকেন, তাহলে আপনার SMTP setup সফলভাবে কাজ করছে।</p>
{_info_card([
    ("Sent at", now_bd_str("%d %b %Y · %I:%M:%S %p")),
    ("Recipient", to),
    ("Test type", "SMTP connectivity"),
])}
"""
    return await send_email(
        to=to,
        subject="✅ SMTP Test — Maxlife88 Agent Portal",
        html=_wrap_html("SMTP Test Successful", body,
                        preheader=f"Your SMTP setup is working — test received at {now_bd_str('%I:%M %p')}."),
        email_type="test",
    )


# ============ Email helpers ============

def _info_card(rows: list, accent: str = "#10B981") -> str:
    """Render a dark info-card with rows of [label, value]."""
    inner = ""
    for label, value in rows:
        inner += (
            f'<tr>'
            f'<td style="padding:12px 18px;color:#64748b;font-size:12px;'
            f'font-weight:600;letter-spacing:0.4px;text-transform:uppercase;'
            f'border-bottom:1px solid rgba(255,255,255,0.04);width:42%;vertical-align:top;">{label}</td>'
            f'<td style="padding:12px 18px;color:#e2e8f0;font-size:13px;'
            f'border-bottom:1px solid rgba(255,255,255,0.04);word-break:break-all;">{value}</td>'
            f'</tr>'
        )
    return (
        f'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" '
        f'style="margin:18px 0;background:#0a1119;border:1px solid rgba(16,185,129,0.18);'
        f'border-left:3px solid {accent};border-radius:12px;overflow:hidden;">'
        f'{inner}'
        f'</table>'
    )


def _cta_button(label: str, url: str, accent: str = "#10B981") -> str:
    return (
        f'<table role="presentation" cellpadding="0" cellspacing="0" border="0" '
        f'style="margin:26px auto;"><tr><td style="border-radius:10px;background:{accent};'
        f'box-shadow:0 8px 24px rgba(16,185,129,0.25);">'
        f'<a href="{url}" target="_blank" rel="noreferrer" '
        f'style="display:inline-block;padding:14px 36px;color:#ffffff;text-decoration:none;'
        f'font-weight:700;font-size:14px;letter-spacing:0.3px;font-family:\'Segoe UI\',Roboto,sans-serif;">'
        f'{label} →</a></td></tr></table>'
    )


def _note_box(text_en: str, text_bn: str, color: str = "#10B981", icon: str = "📎") -> str:
    return (
        f'<div style="margin-top:24px;padding:14px 18px;background:rgba(16,185,129,0.06);'
        f'border:1px solid rgba(16,185,129,0.22);border-radius:12px;'
        f'color:#a7f3d0;font-size:13px;line-height:1.65;">'
        f'<span style="font-size:15px;">{icon}</span> {text_en}<br/>'
        f'<span style="color:#94a3b8;font-size:12px;">{icon} {text_bn}</span>'
        f'</div>'
    )


# ============ Email templates ============

async def send_payment_received_email(to: str, full_name: str, amount: float, payment_id: str, application_id: Optional[str] = None, pdf_bytes: Optional[bytes] = None):
    body = f"""
<p style="margin:0 0 8px 0;color:#e2e8f0;">Hello <strong style="color:#ffffff;">{full_name}</strong>,</p>
<p style="margin:0 0 18px 0;color:#94a3b8;font-size:13px;">হ্যালো <strong>{full_name}</strong>,</p>

<p style="color:#cbd5e1;">We&apos;ve received your USDT payment of <strong style="color:#10B981;">${amount:.2f}</strong>.
Your agent application is now queued for KYC review by our team.</p>
<p style="color:#94a3b8;font-size:13px;">আপনার <strong style="color:#10B981;">${amount:.2f}</strong> USDT পেমেন্ট
সফলভাবে গ্রহণ করা হয়েছে। আপনার এজেন্ট আবেদন এখন আমাদের রিভিউ টিমের কাছে পাঠানো হয়েছে।</p>

{_info_card([
    ("Application ID", f'<span style="font-family:Menlo,Consolas,monospace;color:#10B981;">{application_id or "—"}</span>'),
    ("Payment ID", f'<span style="font-family:Menlo,Consolas,monospace;color:#10B981;">{payment_id}</span>'),
    ("Amount", f'<strong style="color:#10B981;">${amount:.2f} USDT</strong>'),
    ("Status", '<span style="display:inline-block;padding:3px 10px;background:rgba(59,130,246,0.15);color:#60a5fa;border-radius:6px;font-size:11px;font-weight:700;letter-spacing:0.4px;">UNDER REVIEW</span>'),
])}

<p style="color:#cbd5e1;">You&apos;ll receive another email within ~24 hours once an admin approves or rejects your application.</p>
<p style="color:#94a3b8;font-size:13px;">২৪ ঘন্টার মধ্যে অনুমোদন বা প্রত্যাখ্যান সংক্রান্ত আরেকটি ইমেইল পাঠানো হবে।</p>

{_note_box("Your payment receipt is attached as a PDF — keep it for your records.", "আপনার পেমেন্ট রিসিপ্ট PDF আকারে সংযুক্ত করা হয়েছে।") if pdf_bytes else ""}
"""
    attachments = [{"filename": f"payment-receipt-{application_id or ''}.pdf", "content": pdf_bytes, "mime_type": "application/pdf"}] if pdf_bytes else None
    return await send_email(
        to,
        "✓ Payment Received — Maxlife88 Agent Application",
        _wrap_html("Payment received & queued for review", body,
                   preheader=f"Your ${amount:.2f} USDT payment is confirmed. Review starts within 24h."),
        email_type="payment_received",
        application_id=application_id,
        attachments=attachments,
    )


async def send_application_approved_email(to: str, full_name: str, telegram_url: str, application_id: Optional[str] = None, pdf_bytes: Optional[bytes] = None):
    body = f"""
<div style="text-align:center;padding:8px 0 18px 0;">
  <div style="display:inline-block;padding:6px 16px;background:rgba(16,185,129,0.12);
              border:1px solid rgba(16,185,129,0.35);border-radius:999px;color:#10B981;
              font-size:11px;font-weight:700;letter-spacing:1.2px;text-transform:uppercase;">
    🎉 Application Approved
  </div>
</div>

<p style="margin:0 0 6px 0;color:#e2e8f0;font-size:17px;">Congratulations, <strong style="color:#ffffff;">{full_name}</strong> 🎉</p>
<p style="margin:0 0 20px 0;color:#94a3b8;font-size:13px;">অভিনন্দন, <strong>{full_name}</strong> — আপনার আবেদন অনুমোদিত হয়েছে।</p>

<p style="color:#cbd5e1;">Your Maxlife88 Agent application has been <strong style="color:#10B981;">approved</strong>.
Welcome to our agent network — your account is now active.</p>
<p style="color:#94a3b8;font-size:13px;">আপনার Maxlife88 এজেন্ট আবেদন <strong style="color:#10B981;">অনুমোদিত</strong> হয়েছে। আমাদের এজেন্ট নেটওয়ার্কে আপনাকে স্বাগতম।</p>

{_info_card([
    ("Application ID", f'<span style="font-family:Menlo,Consolas,monospace;color:#10B981;">{application_id or "—"}</span>'),
    ("Status", '<span style="display:inline-block;padding:3px 10px;background:rgba(16,185,129,0.15);color:#10B981;border-radius:6px;font-size:11px;font-weight:700;letter-spacing:0.4px;">VERIFIED AGENT</span>'),
    ("Approved On", now_bd_str("%d %b %Y · %I:%M %p")),
])}

<p style="color:#cbd5e1;">Our team will message you on Telegram shortly with your agent credentials and onboarding details.
Please be ready to receive the call within the next few hours.</p>
<p style="color:#94a3b8;font-size:13px;">আমাদের টিম শীঘ্রই Telegram-এ যোগাযোগ করে আপনার এজেন্ট লগইন ক্রেডেনশিয়াল ও পরবর্তী ধাপ জানাবে।</p>

{_cta_button("Contact Manager on Telegram", telegram_url)}

{_note_box("Your official approval certificate is attached as a PDF.", "আপনার অনুমোদন সার্টিফিকেট PDF আকারে সংযুক্ত।", icon="🎖️") if pdf_bytes else ""}
"""
    attachments = [{"filename": f"approval-certificate-{application_id or ''}.pdf", "content": pdf_bytes, "mime_type": "application/pdf"}] if pdf_bytes else None
    return await send_email(
        to,
        "🎉 Approved — Welcome to Maxlife88 Agent Network",
        _wrap_html("Welcome to the agent network", body,
                   preheader="Your KYC has been verified and your agent account is now active."),
        email_type="approved",
        application_id=application_id,
        attachments=attachments,
    )


async def send_application_rejected_email(to: str, full_name: str, reason: str, telegram_url: str, application_id: Optional[str] = None, pdf_bytes: Optional[bytes] = None, reupload_url: Optional[str] = None):
    reupload_cta = ""
    if reupload_url:
        reupload_cta = f"""
<div style="margin:24px 0 8px 0;padding:20px 24px;background:linear-gradient(135deg,rgba(16,185,129,0.10) 0%,rgba(16,185,129,0.04) 100%);
            border:1px solid rgba(16,185,129,0.32);border-radius:14px;">
  <div style="color:#10B981;font-size:11px;font-weight:700;letter-spacing:1.2px;text-transform:uppercase;margin-bottom:6px;">
    ✨ Free Resubmission · ফ্রি পুনরায় আবেদন
  </div>
  <div style="color:#cbd5e1;font-size:14px;line-height:1.6;">
    Re-upload clearer NID photos using the button below — <strong style="color:#10B981;">no additional payment required</strong>.
    Your previous payment is carried forward automatically.
  </div>
  <div style="color:#94a3b8;font-size:12px;line-height:1.5;margin-top:6px;">
    নিচের বাটনে ক্লিক করে স্পষ্ট NID ছবি আপলোড করুন — <strong style="color:#10B981;">পুনরায় পেমেন্ট লাগবে না</strong>। আপনার পূর্ববর্তী পেমেন্ট স্বয়ংক্রিয়ভাবে carry-forward হবে।
  </div>
  {_cta_button("Re-upload NID & Resubmit (No Payment)", reupload_url, accent="#10B981")}
  <div style="text-align:center;margin-top:-12px;">
    <a href="{telegram_url}" target="_blank" rel="noreferrer"
       style="display:inline-block;padding:8px 16px;color:#94a3b8;text-decoration:none;
              font-size:12px;border-bottom:1px dashed rgba(148,163,184,0.4);">
      Or contact support on Telegram →
    </a>
  </div>
</div>
"""
    else:
        reupload_cta = _cta_button("Contact Support on Telegram", telegram_url, accent="#10B981")

    body = f"""
<p style="margin:0 0 8px 0;color:#e2e8f0;">Hello <strong style="color:#ffffff;">{full_name}</strong>,</p>
<p style="margin:0 0 18px 0;color:#94a3b8;font-size:13px;">হ্যালো <strong>{full_name}</strong>,</p>

<p style="color:#cbd5e1;">After careful review of your documents, we&apos;re unable to approve your Maxlife88 Agent application at this time.</p>
<p style="color:#94a3b8;font-size:13px;">সতর্কতার সাথে রিভিউ করার পর দুঃখের সাথে জানানো হচ্ছে যে এই মুহূর্তে আপনার আবেদনটি অনুমোদন করা সম্ভব হয়নি।</p>

<div style="margin:22px 0;padding:18px 22px;background:rgba(239,68,68,0.07);
            border:1px solid rgba(239,68,68,0.28);border-left:3px solid #EF4444;border-radius:12px;">
  <div style="color:#94a3b8;font-size:11px;font-weight:700;letter-spacing:1.2px;
              text-transform:uppercase;margin-bottom:8px;">Reason for Rejection · কারণ</div>
  <div style="color:#fca5a5;font-size:14px;line-height:1.6;">{reason}</div>
</div>

{_info_card([
    ("Application ID", f'<span style="font-family:Menlo,Consolas,monospace;color:#EF4444;">{application_id or "—"}</span>'),
    ("Status", '<span style="display:inline-block;padding:3px 10px;background:rgba(239,68,68,0.15);color:#fca5a5;border-radius:6px;font-size:11px;font-weight:700;letter-spacing:0.4px;">NOT APPROVED</span>'),
    ("Decision Date", now_bd_str("%d %b %Y · %I:%M %p")),
], accent="#EF4444")}

{reupload_cta}

{_note_box("The full application report (with the rejection reason) is attached as a PDF.", "আবেদন রিপোর্ট PDF আকারে সংযুক্ত।") if pdf_bytes else ""}
"""
    attachments = [{"filename": f"application-report-{application_id or ''}.pdf", "content": pdf_bytes, "mime_type": "application/pdf"}] if pdf_bytes else None
    return await send_email(
        to,
        "Application Update — Resubmit Without Re-payment | Maxlife88",
        _wrap_html("Application status update", body, accent="#EF4444",
                   preheader="Your application needs clearer NID photos — resubmit for free using the link inside."),
        email_type="rejected",
        application_id=application_id,
        attachments=attachments,
    )


async def send_admin_new_application_email(to: str, application: dict):
    info_rows = [
        ("Application ID", f'<span style="font-family:Menlo,Consolas,monospace;color:#10B981;">{application.get("id", "")}</span>'),
        ("Name", application.get("full_name", "—")),
        ("Email", application.get("email", "—")),
        ("Phone", application.get("phone", "—")),
        ("Username", application.get("username", "—")),
        ("Telegram", f'@{application.get("telegram_username", "—")}'),
        ("Location", f'{application.get("city","—")}, {application.get("state","—")}'),
        ("Amount Paid", f'<strong style="color:#10B981;">${application.get("price_amount", 0):.2f} USDT</strong>'),
        ("Submitted", fmt_bd_long(application.get("created_at"))),
    ]
    body = f"""
<p style="color:#e2e8f0;">A new paid agent application has just landed in your queue and is ready for KYC review.</p>
<p style="color:#94a3b8;font-size:13px;">নতুন একটি paid এজেন্ট আবেদন এসেছে — রিভিউয়ের অপেক্ষায়।</p>

{_info_card(info_rows)}

<p style="color:#cbd5e1;font-size:14px;">Log in to the admin panel to verify the NID documents and approve / reject this application.</p>
"""
    return await send_email(
        to,
        f"🔔 New Paid Application — {application.get('full_name', '')}",
        _wrap_html("New paid application in queue", body,
                   preheader=f"{application.get('full_name','Agent')} just paid ${application.get('price_amount',0):.2f} — ready for review."),
        email_type="admin_alert",
        application_id=application.get("id"),
    )
