import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from config.settings import settings

def send_email(to_email: str, subject: str, body: str, html_body: str = None):
    """Send an email notification."""
    if not settings.SMTP_USER or not settings.SMTP_PASSWORD:
        print(f"Email configuration missing, skipping email to {to_email}")
        return
    
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = settings.SMTP_FROM
    msg['To'] = to_email
    
    # Add plain text part
    text_part = MIMEText(body, 'plain')
    msg.attach(text_part)
    
    # Add HTML part if provided
    if html_body:
        html_part = MIMEText(html_body, 'html')
        msg.attach(html_part)
    
    try:
        with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT) as server:
            server.starttls()
            server.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
            server.send_message(msg)
        print(f"Email sent successfully to {to_email}")
    except Exception as e:
        print(f"Failed to send email to {to_email}: {e}")

def send_event_notification(to_email: str, event):
    """Send event notification email."""
    subject = f"Nouvel événement: {event.title}"
    
    body = f"""
    Bonjour,
    
    Un nouvel événement a été créé sur LeDiscord:
    
    {event.title}
    Date: {event.date.strftime('%d/%m/%Y à %H:%M')}
    Lieu: {event.location or 'Non spécifié'}
    
    {event.description or ''}
    
    Connectez-vous pour indiquer votre présence: {settings.APP_URL}/events/{event.id}
    
    À bientôt !
    L'équipe LeDiscord
    """
    
    html_body = f"""
    <html>
        <body style="font-family: Arial, sans-serif;">
            <h2>Nouvel événement sur LeDiscord</h2>
            <h3>{event.title}</h3>
            <p><strong>Date:</strong> {event.date.strftime('%d/%m/%Y à %H:%M')}</p>
            <p><strong>Lieu:</strong> {event.location or 'Non spécifié'}</p>
            {f'<p>{event.description}</p>' if event.description else ''}
            <a href="{settings.APP_URL}/events/{event.id}" 
               style="display: inline-block; padding: 10px 20px; background-color: #007bff; color: white; text-decoration: none; border-radius: 5px;">
                Indiquer ma présence
            </a>
        </body>
    </html>
    """
    
    send_email(to_email, subject, body, html_body)
