import aiosmtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from jinja2 import Environment, FileSystemLoader, select_autoescape
import os
from typing import List, Optional, Dict, Any
import logging
from ..core.config import settings

logger = logging.getLogger(__name__)

class EmailService:
    def __init__(self):
        self.smtp_host = settings.smtp_host
        self.smtp_port = settings.smtp_port
        self.smtp_username = settings.smtp_username
        self.smtp_password = settings.smtp_password
        self.smtp_use_tls = settings.smtp_use_tls
        self.smtp_use_ssl = settings.smtp_use_ssl
        self.from_email = settings.email_from
        self.from_name = settings.email_from_name
        
        # Setup Jinja2 for email templates
        template_dir = os.path.join(os.path.dirname(__file__), '../templates')
        self.template_env = Environment(
            loader=FileSystemLoader(template_dir),
            autoescape=select_autoescape(['html', 'xml'])
        )
    
    async def send_email(
        self,
        to_email: str,
        subject: str,
        html_content: str,
        text_content: Optional[str] = None
    ) -> bool:
        """Send an email using SMTP"""
        try:
            # Create message
            message = MIMEMultipart('alternative')
            message['Subject'] = subject
            message['From'] = f"{self.from_name} <{self.from_email}>"
            message['To'] = to_email
            
            # Add plain text part
            if text_content:
                text_part = MIMEText(text_content, 'plain')
                message.attach(text_part)
            
            # Add HTML part
            html_part = MIMEText(html_content, 'html')
            message.attach(html_part)
            
            # Send email using aiosmtplib.send
            await aiosmtplib.send(
                message,
                hostname=self.smtp_host,
                port=self.smtp_port,
                start_tls=True,
                username=self.smtp_username,
                password=self.smtp_password,
            )
            
            logger.info(f"Email sent successfully to {to_email}")
            return True
            
        except Exception as e:
            logger.error(f"Failed to send email to {to_email}: {str(e)}")
            # For development/testing, log the email content instead of failing completely
            logger.info(f"EMAIL CONTENT (DEV MODE): To: {to_email}, Subject: {subject}")
            if html_content:
                logger.info(f"HTML Content Preview: {html_content[:200]}...")
            return False
    
    async def send_verification_email(
        self,
        to_email: str,
        username: str,
        verification_token: str
    ) -> bool:
        """Send email verification link"""
        verification_url = f"{settings.base_url}/verify-email?token={verification_token}"
        
        try:
            template = self.template_env.get_template('email_verification.html')
            html_content = template.render(
                username=username,
                verification_url=verification_url,
                base_url=settings.base_url
            )
        except Exception as e:
            logger.warning(f"Template error, using fallback: {e}")
            html_content = f"""
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Verify Your Email</title>
                <style>
                    body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
                    .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
                    .header {{ background-color: #4CAF50; color: white; text-align: center; padding: 20px; }}
                    .content {{ padding: 20px; background-color: #f9f9f9; }}
                    .button {{ display: inline-block; background-color: #4CAF50; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; }}
                    .footer {{ text-align: center; padding: 20px; font-size: 12px; color: #666; }}
                </style>
            </head>
            <body>
                <div class="container">
                    <div class="header">
                        <h1>Welcome to Mana Pige!</h1>
                    </div>
                    <div class="content">
                        <p>Hi {username},</p>
                        <p>Thank you for signing up! Please verify your email address by clicking the button below:</p>
                        <p style="text-align: center;">
                            <a href="{verification_url}" class="button">Verify Email Address</a>
                        </p>
                        <p>Or copy and paste this link into your browser:</p>
                        <p style="word-break: break-all;">{verification_url}</p>
                        <p><strong>This link will expire in 24 hours.</strong></p>
                        <p>If you didn't create an account, you can safely ignore this email.</p>
                    </div>
                    <div class="footer">
                        <p>Best regards,<br>Mana Pige Team</p>
                    </div>
                </div>
            </body>
            </html>
            """
        
        text_content = f"""
        Hi {username},
        
        Welcome to Mana Pige! Please verify your email address by clicking the link below:
        
        {verification_url}
        
        This link will expire in 24 hours.
        
        If you didn't create an account, please ignore this email.
        
        Best regards,
        Mana Pige Team
        """
        
        return await self.send_email(
            to_email=to_email,
            subject="Verify your Mana Pige account",
            html_content=html_content,
            text_content=text_content
        )
    
    async def send_password_reset_email(
        self,
        to_email: str,
        username: str,
        reset_token: str
    ) -> bool:
        """Send password reset email"""
        reset_url = f"{settings.base_url}/reset-password?token={reset_token}"
        
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Password Reset</title>
            <style>
                body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
                .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
                .header {{ background-color: #f44336; color: white; text-align: center; padding: 20px; }}
                .content {{ padding: 20px; background-color: #f9f9f9; }}
                .button {{ display: inline-block; background-color: #f44336; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; }}
                .footer {{ text-align: center; padding: 20px; font-size: 12px; color: #666; }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>Password Reset Request</h1>
                </div>
                <div class="content">
                    <p>Hi {username},</p>
                    <p>You requested a password reset for your Mana Pige account. Click the button below to reset your password:</p>
                    <p style="text-align: center;">
                        <a href="{reset_url}" class="button">Reset Password</a>
                    </p>
                    <p><strong>This link will expire in 1 hour.</strong></p>
                    <p>If you didn't request this, please ignore this email.</p>
                </div>
                <div class="footer">
                    <p>Best regards,<br>Mana Pige Team</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        text_content = f"""
        Hi {username},
        
        You requested a password reset for your Mana Pige account. Click the link below to reset your password:
        
        {reset_url}
        
        This link will expire in 1 hour.
        
        If you didn't request this, please ignore this email.
        
        Best regards,
        Mana Pige Team
        """
        
        return await self.send_email(
            to_email=to_email,
            subject="Reset your Mana Pige password",
            html_content=html_content,
            text_content=text_content
        )
    
    async def send_welcome_email(
        self,
        to_email: str,
        username: str
    ) -> bool:
        """Send welcome email after successful verification"""
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Welcome to Mana Pige</title>
            <style>
                body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
                .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
                .header {{ background-color: #2196F3; color: white; text-align: center; padding: 20px; }}
                .content {{ padding: 20px; background-color: #f9f9f9; }}
                .button {{ display: inline-block; background-color: #2196F3; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; }}
                .footer {{ text-align: center; padding: 20px; font-size: 12px; color: #666; }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>Welcome to Mana Pige!</h1>
                </div>
                <div class="content">
                    <p>Hi {username},</p>
                    <p>Your account has been successfully verified. You can now log in and start using all our features.</p>
                    <p style="text-align: center;">
                        <a href="{settings.base_url}" class="button">Get Started</a>
                    </p>
                </div>
                <div class="footer">
                    <p>Best regards,<br>Mana Pige Team</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        text_content = f"""
        Hi {username},
        
        Welcome to Mana Pige! Your account has been successfully verified.
        
        You can now log in and start using all our features.
        
        Visit: {settings.base_url}
        
        Best regards,
        Mana Pige Team
        """
        
        return await self.send_email(
            to_email=to_email,
            subject="Welcome to Mana Pige!",
            html_content=html_content,
            text_content=text_content
        )

# Global email service instance
email_service = EmailService()
