from django.conf import settings
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.utils.html import strip_tags
from django.utils.http import urlsafe_base64_encode


def _build_email(subject, html_content, to_email):
    """Helper to build and send an email with HTML + plaintext fallback."""
    text_content = strip_tags(html_content)
    email = EmailMultiAlternatives(
        subject=subject,
        body=text_content,
        from_email=settings.DEFAULT_FROM_EMAIL,
        to=[to_email],
    )
    email.attach_alternative(html_content, "text/html")
    return email


def send_email_verification(user):
    """
    Send email verification link after registration.
    The email includes the QR code as an attachment.
    """
    uid = urlsafe_base64_encode(force_bytes(user.pk))
    token = default_token_generator.make_token(user)

    verify_url = (
        f"{settings.FRONTEND_PROTOCOL}://{settings.FRONTEND_DOMAIN}"
        f"/account/verify-email?uid={uid}&token={token}"
    )

    html_content = f"""
    <!DOCTYPE html>
    <html lang="fr">
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ background-color: #f9fafb; font-family: 'Helvetica Neue', Arial, sans-serif; color: #333; margin: 0; padding: 0; }}
            .container {{ max-width: 600px; margin: 30px auto; background: #fff; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); overflow: hidden; }}
            .header {{ background-color: #1e3a5f; color: white; text-align: center; padding: 25px; }}
            .header h1 {{ margin: 0; font-size: 22px; }}
            .content {{ padding: 30px; line-height: 1.6; }}
            .button {{ display: inline-block; background-color: #1e3a5f; color: white !important; padding: 14px 28px; border-radius: 6px; text-decoration: none; margin-top: 15px; font-weight: bold; }}
            .info-box {{ background: #f0f4f8; border-left: 4px solid #1e3a5f; padding: 15px; margin: 20px 0; border-radius: 4px; }}
            .footer {{ background: #f3f4f6; text-align: center; padding: 15px; font-size: 13px; color: #6b7280; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>✉️ Vérification de votre email — APECB</h1>
            </div>
            <div class="content">
                <p>Bonjour <strong>{user.get_full_name() or user.email}</strong>,</p>
                <p>Merci pour votre inscription à l'APECB. Veuillez confirmer votre adresse email en cliquant sur le bouton ci-dessous :</p>
                <p style="text-align:center;">
                    <a href="{verify_url}" class="button">Vérifier mon email</a>
                </p>
                <div class="info-box">
                    <strong>📋 Prochaines étapes après vérification :</strong><br>
                    1. Vous recevrez votre <strong>QR code d'adhérent</strong> par email<br>
                    2. Effectuez le paiement des frais d'adhésion<br>
                    3. Déposez le reçu avec votre QR code à l'administration<br>
                    4. Votre compte sera activé par l'agent
                </div>
                <p>Votre numéro d'adhérent : <strong>{user.membership_id}</strong></p>
                <p style="color: #888; font-size: 13px;">Si vous n'avez pas créé de compte, ignorez cet email.</p>
            </div>
            <div class="footer">
                © APECB — Association Professionnelle<br>
                Ceci est un email automatique.
            </div>
        </div>
    </body>
    </html>
    """

    email = _build_email(
        subject="✉️ APECB — Vérifiez votre adresse email",
        html_content=html_content,
        to_email=user.email,
    )

    # Attach QR code image if it exists
    if user.qr_code:
        try:
            user.qr_code.open('rb')
            email.attach(
                f"qr_code_{user.membership_id}.png",
                user.qr_code.read(),
                "image/png",
            )
            user.qr_code.close()
        except Exception as e:
            print(f"Error attaching QR code to verification email: {e}")

    email.send(fail_silently=False)


def send_qr_code_email(user):
    """
    Send the QR code to the user after email verification.
    Attaches the QR code image to the email.
    """
    html_content = f"""
    <!DOCTYPE html>
    <html lang="fr">
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ background-color: #f9fafb; font-family: 'Helvetica Neue', Arial, sans-serif; color: #333; margin: 0; padding: 0; }}
            .container {{ max-width: 600px; margin: 30px auto; background: #fff; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); overflow: hidden; }}
            .header {{ background-color: #1e3a5f; color: white; text-align: center; padding: 25px; }}
            .header h1 {{ margin: 0; font-size: 22px; }}
            .content {{ padding: 30px; line-height: 1.6; }}
            .info-box {{ background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px; }}
            .steps {{ background: #f0f4f8; padding: 20px; border-radius: 8px; margin: 20px 0; }}
            .footer {{ background: #f3f4f6; text-align: center; padding: 15px; font-size: 13px; color: #6b7280; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>📱 Votre QR Code d'Adhésion — APECB</h1>
            </div>
            <div class="content">
                <p>Bonjour <strong>{user.get_full_name() or user.email}</strong>,</p>
                <p>Votre email a été vérifié avec succès ! ✅</p>
                <p>Vous trouverez ci-joint votre <strong>QR code d'adhérent</strong>.</p>

                <div class="info-box">
                    <strong>⚠️ Important :</strong><br>
                    Votre numéro d'adhérent : <strong>{user.membership_id}</strong><br>
                    Imprimez ou conservez votre QR code.
                </div>

                <div class="steps">
                    <strong>📋 Pour finaliser votre adhésion :</strong><br><br>
                    1. Effectuez le paiement des frais d'adhésion<br>
                    2. Présentez-vous à l'administration avec :<br>
                    &nbsp;&nbsp;&nbsp;— Le reçu de paiement<br>
                    &nbsp;&nbsp;&nbsp;— Votre QR code (imprimé ou sur téléphone)<br>
                    3. L'agent validera votre compte<br>
                    4. Vous recevrez un email de confirmation
                </div>
            </div>
            <div class="footer">
                © APECB — Association Professionnelle<br>
                Ceci est un email automatique.
            </div>
        </div>
    </body>
    </html>
    """

    email = _build_email(
        subject="📱 APECB — Votre QR Code d'Adhésion",
        html_content=html_content,
        to_email=user.email,
    )

    # Attach QR code image
    if user.qr_code:
        user.qr_code.open('rb')
        email.attach(
            f"qr_code_{user.membership_id}.png",
            user.qr_code.read(),
            "image/png",
        )
        user.qr_code.close()

    email.send(fail_silently=False)


def send_account_activated_email(user):
    """
    Send email notification when the agent activates the user's account.
    """
    login_url = f"{settings.FRONTEND_PROTOCOL}://{settings.FRONTEND_DOMAIN}/account/connection"

    html_content = f"""
    <!DOCTYPE html>
    <html lang="fr">
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ background-color: #f9fafb; font-family: 'Helvetica Neue', Arial, sans-serif; color: #333; margin: 0; padding: 0; }}
            .container {{ max-width: 600px; margin: 30px auto; background: #fff; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); overflow: hidden; }}
            .header {{ background-color: #28a745; color: white; text-align: center; padding: 25px; }}
            .header h1 {{ margin: 0; font-size: 22px; }}
            .content {{ padding: 30px; line-height: 1.6; }}
            .button {{ display: inline-block; background-color: #28a745; color: white !important; padding: 14px 28px; border-radius: 6px; text-decoration: none; margin-top: 15px; font-weight: bold; }}
            .footer {{ background: #f3f4f6; text-align: center; padding: 15px; font-size: 13px; color: #6b7280; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>🎉 Compte Activé — APECB</h1>
            </div>
            <div class="content">
                <p>Bonjour <strong>{user.get_full_name() or user.email}</strong>,</p>
                <p>Excellente nouvelle ! Votre compte APECB a été <strong>activé avec succès</strong> par notre administration.</p>
                <p>Vous pouvez maintenant vous connecter et accéder à votre espace adhérent :</p>
                <p style="text-align:center;">
                    <a href="{login_url}" class="button">Se connecter</a>
                </p>
                <p>Si vous n'avez pas encore défini votre mot de passe, utilisez la fonctionnalité "Mot de passe oublié" pour en créer un.</p>
                <p>Bienvenue dans la communauté APECB ! 🎉</p>
            </div>
            <div class="footer">
                © APECB — Association Professionnelle<br>
                Ceci est un email automatique.
            </div>
        </div>
    </body>
    </html>
    """

    email = _build_email(
        subject="🎉 APECB — Votre compte est maintenant actif !",
        html_content=html_content,
        to_email=user.email,
    )
    email.send(fail_silently=False)


def send_password_reset_email(user):
    """
    Send password reset link.
    Used by both the API view and the admin action.
    """
    uid = urlsafe_base64_encode(force_bytes(user.pk))
    token = default_token_generator.make_token(user)

    reset_url = (
        f"{settings.FRONTEND_PROTOCOL}://{settings.FRONTEND_DOMAIN}"
        f"/account/reset_password_form?uid={uid}&token={token}"
    )

    html_content = f"""
    <!DOCTYPE html>
    <html lang="fr">
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ background-color: #f9fafb; font-family: 'Helvetica Neue', Arial, sans-serif; color: #333; margin: 0; padding: 0; }}
            .container {{ max-width: 600px; margin: 30px auto; background: #fff; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); overflow: hidden; }}
            .header {{ background-color: #4F46E5; color: white; text-align: center; padding: 25px; }}
            .header h1 {{ margin: 0; font-size: 22px; }}
            .content {{ padding: 30px; line-height: 1.6; }}
            .button {{ display: inline-block; background-color: #4F46E5; color: white !important; padding: 14px 28px; border-radius: 6px; text-decoration: none; margin-top: 15px; font-weight: bold; }}
            .footer {{ background: #f3f4f6; text-align: center; padding: 15px; font-size: 13px; color: #6b7280; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>🔐 Réinitialisation de votre mot de passe</h1>
            </div>
            <div class="content">
                <p>Bonjour <strong>{user.get_full_name() or user.email}</strong>,</p>
                <p>Vous avez demandé à réinitialiser votre mot de passe. Cliquez sur le bouton ci-dessous :</p>
                <p style="text-align:center;">
                    <a href="{reset_url}" class="button">Réinitialiser mon mot de passe</a>
                </p>
                <p>Si vous n'êtes pas à l'origine de cette demande, ignorez cet email.</p>
                <p style="color: #888; font-size: 13px;">Ce lien expirera après un certain temps pour des raisons de sécurité.</p>
            </div>
            <div class="footer">
                © APECB — Association Professionnelle<br>
                Ceci est un email automatique.
            </div>
        </div>
    </body>
    </html>
    """

    email = _build_email(
        subject="🔐 APECB — Réinitialisation de votre mot de passe",
        html_content=html_content,
        to_email=user.email,
    )
    email.send(fail_silently=False)
