import logging
from html import escape

from django.conf import settings
from django.core.mail import EmailMultiAlternatives

logger = logging.getLogger(__name__)


def send_invoice_email(invoice, recipient_email: str | None = None) -> bool:
    """Send an invoice email via the configured provider. Returns True if sent."""
    if not recipient_email or not getattr(settings, 'EMAIL_ENABLED', False):
        return False

    from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', 'no-reply@fudo.local')

    try:
        invoice_number = escape(str(invoice.invoice_number))
        customer_name = escape(str(invoice.customer_name))
        currency = escape(str(invoice.currency))
        line_rows = []
        text_lines = []
        for line in invoice.lines.all():
            description = escape(str(line.description))
            line_total = f"{line.total:.2f}"
            line_rows.append(
                f'<tr><td style="padding: 10px 0; border-bottom: 1px solid #e2e8f0;">{description}</td>'
                f'<td style="padding: 10px 0; text-align: right; border-bottom: 1px solid #e2e8f0;">'
                f'{line.quantity} x {line.unit_price:.2f} = {line_total} {currency}</td></tr>'
            )
            text_lines.append(
                f"- {line.description}: {line.quantity} x {line.unit_price:.2f} = "
                f"{line_total} {invoice.currency}"
            )

        subject = f"Invoice {invoice.invoice_number} - {invoice.customer_name}"
        text_body = (
            f"Hello {invoice.customer_name},\n\n"
            f"Your invoice {invoice.invoice_number} has been issued.\n\n"
            + "\n".join(text_lines)
            + f"\n\nSubtotal: {invoice.subtotal:.2f} {invoice.currency}\n"
            f"Tax: {invoice.tax_total:.2f} {invoice.currency}\n"
            f"Total: {invoice.total_amount:.2f} {invoice.currency}\n"
            f"Due date: {invoice.due_date}\n\n"
            f"Thank you for your business.\nRegards,\nFUDO ERP"
        )
        html_body = f"""
        <html><body style="font-family: Arial, sans-serif; color: #0f172a; line-height: 1.6;">
          <div style="max-width: 640px; margin: 0 auto; padding: 24px; border: 1px solid #e2e8f0; border-radius: 12px;">
            <h2 style="margin: 0 0 12px;">Invoice {invoice_number}</h2>
            <p>Hello {customer_name},</p>
            <p>Your invoice has been issued for <strong>{invoice.total_amount:.2f} {currency}</strong>.</p>
            <table style="width: 100%; border-collapse: collapse; margin: 24px 0;">
              <thead><tr><th style="text-align: left;">Description</th><th style="text-align: right;">Amount</th></tr></thead>
              <tbody>{''.join(line_rows)}</tbody>
            </table>
            <p style="text-align: right;"><strong>Subtotal:</strong> {invoice.subtotal:.2f} {currency}<br />
            <strong>Tax:</strong> {invoice.tax_total:.2f} {currency}<br />
            <strong>Total:</strong> {invoice.total_amount:.2f} {currency}</p>
            <p><strong>Due date:</strong> {invoice.due_date}<br /><strong>Status:</strong> {escape(str(invoice.status))}</p>
            <p>Thank you for your business.</p><p>Regards,<br />FUDO ERP</p>
          </div>
        </body></html>
        """

        message = EmailMultiAlternatives(
            subject=subject,
            body=text_body,
            from_email=from_email,
            to=[recipient_email],
        )
        message.attach_alternative(html_body, 'text/html')
        return message.send() > 0
    except Exception as exc:  # pragma: no cover - provider failures fail softly
        logger.exception(
            "Failed to send invoice email for invoice %s: %s",
            getattr(invoice, 'id', 'unknown'),
            exc,
        )
        return False
