from django.core.mail import send_mail
from django.conf import settings
from django.urls import reverse
from django.template.loader import render_to_string


def send_token_email(user, token_obj):
    """Envoie un email avec le lien de vérification du token."""
    # Construire l'URL de vérification
    verify_url = f"{settings.SITE_URL}/accounts/verify-token/?token={token_obj.token}"
    
    subject = "Votre lien de connexion"
    
    # Message texte
    message = f"""
Bonjour,

Vous avez demandé un lien de connexion pour accéder à l'application.

Cliquez sur le lien ci-dessous pour vous connecter (valable 8 heures) :
{verify_url}

Si vous n'avez pas fait cette demande, ignorez cet email.

Cordialement,
L'équipe
    """
    
    # Message HTML (optionnel)
    html_message = f"""
    <html>
    <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
        <div style="max-width: 600px; margin: 0 auto; padding: 20px; background: #f9f9f9; border-radius: 10px;">
            <h2 style="color: #667eea;">Connexion à votre compte</h2>
            <p>Bonjour,</p>
            <p>Vous avez demandé un lien de connexion pour accéder à l'application.</p>
            <div style="text-align: center; margin: 30px 0;">
                <a href="{verify_url}" 
                   style="display: inline-block; padding: 15px 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                          color: white; text-decoration: none; border-radius: 50px; font-weight: bold;">
                    Se connecter maintenant
                </a>
            </div>
            <p style="color: #666; font-size: 14px;">
                <strong>Ce lien est valable pendant 8 heures.</strong>
            </p>
            <p style="color: #999; font-size: 12px; margin-top: 30px;">
                Si vous n'avez pas fait cette demande, ignorez cet email.
            </p>
        </div>
    </body>
    </html>
    """
    
    try:
        send_mail(
            subject=subject,
            message=message,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[user.email],
            html_message=html_message,
            fail_silently=False,
        )
        return True
    except Exception as e:
        print(f"Erreur lors de l'envoi de l'email: {e}")
        return False
