"""Email service for sending verification codes."""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from flask import current_app


def send_email(to_email, subject, body, html_body=None):
    """
    Send a generic email.
    
    Args:
        to_email: Recipient email address
        subject: Email subject
        body: Plain text email body
        html_body: Optional HTML email body
        
    Returns:
        bool: True if email sent successfully, False otherwise
    """
    try:
        # Check if email is configured
        if not current_app.config['MAIL_USERNAME'] or not current_app.config['MAIL_PASSWORD']:
            # Development mode - log the email instead
            current_app.logger.info(f"=== EMAIL (Development Mode) ===")
            current_app.logger.info(f"To: {to_email}")
            current_app.logger.info(f"Subject: {subject}")
            current_app.logger.info(f"Body: {body}")
            current_app.logger.info(f"================================")
            return True
        
        # Create message
        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = current_app.config['MAIL_DEFAULT_SENDER']
        msg['To'] = to_email
        
        # Attach plain text body
        text_part = MIMEText(body, 'plain')
        msg.attach(text_part)
        
        # Attach HTML body if provided
        if html_body:
            html_part = MIMEText(html_body, 'html')
            msg.attach(html_part)
        
        # Send email
        if current_app.config.get('MAIL_USE_SSL'):
            # Port 465 - use SMTP_SSL (implicit SSL)
            with smtplib.SMTP_SSL(current_app.config['MAIL_SERVER'], current_app.config['MAIL_PORT']) as server:
                server.login(
                    current_app.config['MAIL_USERNAME'],
                    current_app.config['MAIL_PASSWORD']
                )
                server.send_message(msg)
        else:
            # Port 587 - use SMTP with STARTTLS (explicit TLS)
            with smtplib.SMTP(current_app.config['MAIL_SERVER'], current_app.config['MAIL_PORT']) as server:
                server.starttls()
                server.login(
                    current_app.config['MAIL_USERNAME'],
                    current_app.config['MAIL_PASSWORD']
                )
                server.send_message(msg)
        
        current_app.logger.info(f"Email sent to {to_email}: {subject}")
        return True
        
    except Exception as e:
        current_app.logger.error(f"Failed to send email to {to_email}: {str(e)}")
        return False


def send_verification_email(email, code):
    """
    Send verification code to user's email.
    
    Args:
        email: Recipient email address
        code: 6-digit verification code
        
    Returns:
        bool: True if email sent successfully, False otherwise
    """
    try:
        # Email content
        subject = "Verify Your Email - AFFIX WEB ADVERTS Rental Platform"
        html_body = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
                .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
                .header {{ background: #000; color: #fff; padding: 20px; text-align: center; }}
                .content {{ padding: 30px; background: #f9f9f9; }}
                .code {{ 
                    font-size: 32px; 
                    font-weight: bold; 
                    letter-spacing: 5px; 
                    color: #000; 
                    text-align: center; 
                    padding: 20px; 
                    background: #fff; 
                    border: 2px solid #000; 
                    margin: 20px 0;
                }}
                .footer {{ text-align: center; padding: 20px; color: #666; font-size: 12px; }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>AFFIX WEB ADVERTS Email Verification</h1>
                </div>
                <div class="content">
                    <p>Hello,</p>
                    <p>Thank you for registering with <b>AFFIX WEB ADVERTS</b> Rental Platform! Please use the verification code below to complete your registration:</p>
                    <div class="code">{code}</div>
                    <p>This code will expire in 30 minutes.</p>
                    <p>If you didn't request this verification, please ignore this email.</p>
                </div>
                <div class="footer">
                    <p>&copy; 2024 Rental Platform. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        # Check if email is configured
        if not current_app.config['MAIL_USERNAME'] or not current_app.config['MAIL_PASSWORD']:
            # Development mode - log the code instead
            current_app.logger.info(f"=== EMAIL VERIFICATION CODE ===")
            current_app.logger.info(f"To: {email}")
            current_app.logger.info(f"Code: {code}")
            current_app.logger.info(f"===============================")
            return True
        
        # Create message
        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = current_app.config['MAIL_DEFAULT_SENDER']
        msg['To'] = email
        
        # Attach HTML body
        html_part = MIMEText(html_body, 'html')
        msg.attach(html_part)
        
        # Send email - CORRECTED SECTION
        if current_app.config.get('MAIL_USE_SSL'):
            # Port 465 - use SMTP_SSL (implicit SSL)
            with smtplib.SMTP_SSL(current_app.config['MAIL_SERVER'], current_app.config['MAIL_PORT']) as server:
                server.login(
                    current_app.config['MAIL_USERNAME'],
                    current_app.config['MAIL_PASSWORD']
                )
                server.send_message(msg)
        else:
            # Port 587 - use SMTP with STARTTLS (explicit TLS)
            with smtplib.SMTP(current_app.config['MAIL_SERVER'], current_app.config['MAIL_PORT']) as server:
                server.starttls()
                server.login(
                    current_app.config['MAIL_USERNAME'],
                    current_app.config['MAIL_PASSWORD']
                )
                server.send_message(msg)
        
        current_app.logger.info(f"Verification email sent to {email}")
        return True

    except Exception as e:
        current_app.logger.error(f"Failed to send verification email to {email}: {str(e)}")
        return False


def send_password_reset_email(email, code):
    """
    Send password reset code to user's email.

    Args:
        email: Recipient email address
        code: 6-digit reset code

    Returns:
        bool: True if email sent successfully, False otherwise
    """
    try:
        # Email content
        subject = "Password Reset - AFFIX WEB ADVERTS Rental Platform"
        html_body = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
                .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
                .header {{ background: #dc2626; color: #fff; padding: 20px; text-align: center; }}
                .content {{ padding: 30px; background: #f9f9f9; }}
                .code {{
                    font-size: 32px;
                    font-weight: bold;
                    letter-spacing: 5px;
                    color: #dc2626;
                    text-align: center;
                    padding: 20px;
                    background: #fff;
                    border: 2px solid #dc2626;
                    margin: 20px 0;
                }}
                .warning {{
                    background: #fef3c7;
                    border-left: 4px solid #f59e0b;
                    padding: 15px;
                    margin: 20px 0;
                }}
                .footer {{ text-align: center; padding: 20px; color: #666; font-size: 12px; }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>Password Reset Request</h1>
                </div>
                <div class="content">
                    <p>Hello,</p>
                    <p>We received a request to reset your password for your <b>AFFIX WEB ADVERTS</b> account. Use the code below to reset your password:</p>
                    <div class="code">{code}</div>
                    <p><strong>This code will expire in 15 minutes.</strong></p>
                    <div class="warning">
                        <strong>Security Notice:</strong> If you did not request a password reset, please ignore this email. Your password will remain unchanged.
                    </div>
                    <p>For security reasons, never share this code with anyone. Our team will never ask for your reset code.</p>
                </div>
                <div class="footer">
                    <p>&copy; 2024 AFFIX WEB ADVERTS Rental Platform. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        """

        # Check if email is configured
        if not current_app.config['MAIL_USERNAME'] or not current_app.config['MAIL_PASSWORD']:
            # Development mode - log the code instead
            current_app.logger.info(f"=== PASSWORD RESET CODE ===")
            current_app.logger.info(f"To: {email}")
            current_app.logger.info(f"Code: {code}")
            current_app.logger.info(f"===========================")
            return True

        # Create message
        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = current_app.config['MAIL_DEFAULT_SENDER']
        msg['To'] = email

        # Attach HTML body
        html_part = MIMEText(html_body, 'html')
        msg.attach(html_part)

        # Send email
        if current_app.config.get('MAIL_USE_SSL'):
            # Port 465 - use SMTP_SSL (implicit SSL)
            with smtplib.SMTP_SSL(current_app.config['MAIL_SERVER'], current_app.config['MAIL_PORT']) as server:
                server.login(
                    current_app.config['MAIL_USERNAME'],
                    current_app.config['MAIL_PASSWORD']
                )
                server.send_message(msg)
        else:
            # Port 587 - use SMTP with STARTTLS (explicit TLS)
            with smtplib.SMTP(current_app.config['MAIL_SERVER'], current_app.config['MAIL_PORT']) as server:
                server.starttls()
                server.login(
                    current_app.config['MAIL_USERNAME'],
                    current_app.config['MAIL_PASSWORD']
                )
                server.send_message(msg)

        current_app.logger.info(f"Password reset email sent to {email}")
        return True

    except Exception as e:
        current_app.logger.error(f"Failed to send password reset email to {email}: {str(e)}")
        return False