"""
Email service for BookBeach application
"""
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from typing import Optional, Dict, Any
from datetime import datetime, timedelta
import random
import string
from sqlalchemy.orm import Session

from app.core.config import settings
from app.models.user import EmailVerificationToken
from app.models.system import EmailTemplate, EmailLog


class EmailService:
    """Email service for sending verification codes and other emails"""
    
    def __init__(self):
        self.smtp_server = settings.MAIL_SERVER
        self.smtp_port = settings.MAIL_PORT
        self.username = settings.MAIL_USERNAME
        self.password = settings.MAIL_PASSWORD
        self.from_email = settings.MAIL_FROM
        self.from_name = settings.MAIL_FROM_NAME
    
    def send_email(
        self, 
        to_email: str, 
        subject: str, 
        html_content: str, 
        text_content: Optional[str] = None
    ) -> bool:
        """Send email using SMTP"""
        try:
            # Create message
            msg = MIMEMultipart('alternative')
            msg['Subject'] = subject
            msg['From'] = f"{self.from_name} <{self.from_email}>"
            msg['To'] = to_email
            
            # Add text content
            if text_content:
                text_part = MIMEText(text_content, 'plain', 'utf-8')
                msg.attach(text_part)
            
            # Add HTML content
            html_part = MIMEText(html_content, 'html', 'utf-8')
            msg.attach(html_part)
            
            # Create secure connection and send email
            context = ssl.create_default_context()
            
            with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:
                server.starttls(context=context)
                server.login(self.username, self.password)
                server.send_message(msg)
            
            return True
            
        except Exception as e:
            print(f"Error sending email: {e}")
            return False
    
    def generate_verification_code(self, length: int = 6) -> str:
        """Generate random 6-digit verification code"""
        return ''.join(random.choices(string.digits, k=length))
    
    def send_verification_email(
        self, 
        db: Session,
        user_id: str, 
        email: str, 
        user_name: str = "User"
    ) -> tuple[bool, str]:
        """Send email verification code"""
        try:
            # Generate verification code
            verification_code = self.generate_verification_code()
            
            # Create verification token in database
            expires_at = datetime.utcnow() + timedelta(
                minutes=settings.EMAIL_VERIFICATION_TOKEN_EXPIRE_MINUTES
            )
            
            token = EmailVerificationToken(
                user_id=user_id,
                token=verification_code,
                token_type="email_verification",
                expires_at=expires_at,
                is_used=False
            )
            
            db.add(token)
            db.commit()
            
            # Prepare email content
            subject = "Welcome to BookBeach - Verify Your Email"
            
            html_content = self._get_verification_email_template(
                user_name=user_name,
                verification_code=verification_code
            )
            
            text_content = f"""
            Welcome to BookBeach!
            
            Hello {user_name},
            
            Thank you for registering with BookBeach. To complete your registration, please use the following verification code:
            
            Verification Code: {verification_code}
            
            This code will expire in {settings.EMAIL_VERIFICATION_TOKEN_EXPIRE_MINUTES} minutes.
            
            If you didn't request this verification, please ignore this email.
            
            Best regards,
            The BookBeach Team
            """
            
            # Send email
            success = self.send_email(email, subject, html_content, text_content)
            
            # Log email attempt
            email_log = EmailLog(
                recipient_email=email,
                subject=subject,
                status='sent' if success else 'failed',
                error_message=None if success else 'Failed to send email',
                sent_at=datetime.utcnow() if success else None
            )
            
            db.add(email_log)
            db.commit()
            
            return success, verification_code
            
        except Exception as e:
            print(f"Error sending verification email: {e}")
            return False, ""
    
    def send_company_evaluation_notification(
        self,
        company_name: str,
        company_email: str,
        contact_person: str
    ) -> bool:
        """Send notification to evaluation team about new company registration"""
        try:
            subject = f"New Company Registration: {company_name}"
            
            html_content = f"""
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <style>
                    body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
                    .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
                    .header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }}
                    .content {{ background: #f8f9fa; padding: 30px; border-radius: 0 0 8px 8px; }}
                    .info-box {{ background: white; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #007bff; }}
                </style>
            </head>
            <body>
                <div class="container">
                    <div class="header">
                        <h1>🏢 New Company Registration</h1>
                    </div>
                    <div class="content">
                        <p>Hello Evaluation Team,</p>
                        
                        <p>A new company has registered on the BookBeach platform and requires evaluation:</p>
                        
                        <div class="info-box">
                            <h3>Company Details:</h3>
                            <p><strong>Company Name:</strong> {company_name}</p>
                            <p><strong>Contact Person:</strong> {contact_person}</p>
                            <p><strong>Email:</strong> {company_email}</p>
                            <p><strong>Registration Date:</strong> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
                        </div>
                        
                        <p>Please review the company details and contact them within 1-2 working days for evaluation.</p>
                        
                        <p>You can access the admin panel to view full company details and manage the approval process.</p>
                        
                        <p>Best regards,<br>
                        BookBeach System</p>
                    </div>
                </div>
            </body>
            </html>
            """
            
            # Send to evaluation team
            return self.send_email(
                settings.EVALUATION_EMAIL,
                subject,
                html_content
            )
            
        except Exception as e:
            print(f"Error sending evaluation notification: {e}")
            return False
    
    def _get_verification_email_template(
        self, 
        user_name: str, 
        verification_code: str
    ) -> str:
        """Get beautiful HTML email template for verification"""
        return f"""
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Verify Your Email - BookBeach</title>
            <style>
                body {{
                    margin: 0;
                    padding: 0;
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    background-color: #f0f8ff;
                    color: #333;
                }}
                .container {{
                    max-width: 600px;
                    margin: 0 auto;
                    background-color: #ffffff;
                    border-radius: 12px;
                    overflow: hidden;
                    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
                }}
                .header {{
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: #ffffff;
                    padding: 40px 30px;
                    text-align: center;
                }}
                .header h1 {{
                    margin: 0;
                    font-size: 28px;
                    font-weight: 600;
                }}
                .header .icon {{
                    font-size: 48px;
                    margin-bottom: 20px;
                }}
                .content {{
                    padding: 40px 30px;
                }}
                .welcome {{
                    font-size: 18px;
                    margin-bottom: 20px;
                    color: #2c3e50;
                }}
                .verification-box {{
                    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
                    color: #ffffff;
                    padding: 30px;
                    border-radius: 12px;
                    text-align: center;
                    margin: 30px 0;
                }}
                .verification-code {{
                    font-size: 36px;
                    font-weight: bold;
                    letter-spacing: 8px;
                    margin: 20px 0;
                    font-family: 'Courier New', monospace;
                    background: rgba(255, 255, 255, 0.2);
                    padding: 15px 25px;
                    border-radius: 8px;
                    border: 2px dashed rgba(255, 255, 255, 0.5);
                }}
                .expiry-info {{
                    background: #e8f4fd;
                    border-left: 4px solid #3498db;
                    padding: 15px 20px;
                    margin: 20px 0;
                    border-radius: 0 8px 8px 0;
                }}
                .footer {{
                    background: #2c3e50;
                    color: #ffffff;
                    padding: 20px 30px;
                    text-align: center;
                    font-size: 14px;
                }}
                .footer a {{
                    color: #3498db;
                    text-decoration: none;
                }}
                .features {{
                    display: flex;
                    justify-content: space-around;
                    margin: 30px 0;
                    flex-wrap: wrap;
                }}
                .feature {{
                    text-align: center;
                    flex: 1;
                    min-width: 150px;
                    margin: 10px;
                }}
                .feature-icon {{
                    font-size: 24px;
                    margin-bottom: 10px;
                    color: #667eea;
                }}
                @media (max-width: 600px) {{
                    .container {{
                        margin: 10px;
                        border-radius: 8px;
                    }}
                    .content {{
                        padding: 20px 15px;
                    }}
                    .verification-code {{
                        font-size: 28px;
                        letter-spacing: 4px;
                    }}
                    .features {{
                        flex-direction: column;
                    }}
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <div class="icon">🏖️</div>
                    <h1>Welcome to BookBeach!</h1>
                    <p>Your beach booking adventure starts here</p>
                </div>
                
                <div class="content">
                    <div class="welcome">
                        Hello <strong>{user_name}</strong>,
                    </div>
                    
                    <p>Thank you for joining BookBeach, the premier platform for booking beautiful beach experiences! We're excited to have you as part of our community.</p>
                    
                    <p>To complete your registration and start exploring amazing beaches, please verify your email address using the verification code below:</p>
                    
                    <div class="verification-box">
                        <h3>📧 Email Verification Code</h3>
                        <div class="verification-code">{verification_code}</div>
                        <p>Enter this code to verify your account</p>
                    </div>
                    
                    <div class="expiry-info">
                        <strong>⏰ Important:</strong> This verification code will expire in {settings.EMAIL_VERIFICATION_TOKEN_EXPIRE_MINUTES} minutes. Please complete your verification soon!
                    </div>
                    
                    <div class="features">
                        <div class="feature">
                            <div class="feature-icon">🌊</div>
                            <h4>Discover Beaches</h4>
                            <p>Find the perfect beach for your next adventure</p>
                        </div>
                        <div class="feature">
                            <div class="feature-icon">📅</div>
                            <h4>Easy Booking</h4>
                            <p>Reserve your spot with just a few clicks</p>
                        </div>
                        <div class="feature">
                            <div class="feature-icon">⭐</div>
                            <h4>Premium Experience</h4>
                            <p>Enjoy top-quality beach services</p>
                        </div>
                    </div>
                    
                    <p>If you didn't create this account, please ignore this email and the account will remain unverified.</p>
                    
                    <p>Have questions? We're here to help! Contact our support team anytime.</p>
                    
                    <p>Welcome aboard!</p>
                    <p><strong>The BookBeach Team</strong></p>
                </div>
                
                <div class="footer">
                    <p>&copy; 2024 BookBeach. All rights reserved.</p>
                    <p>
                        <a href="mailto:{settings.SUPPORT_EMAIL}">Support</a> |
                        <a href="https://bookbeach.app">Website</a> |
                        <a href="https://bookbeach.app/privacy">Privacy Policy</a>
                    </p>
                </div>
            </div>
        </body>
        </html>
        """


# Global email service instance
email_service = EmailService()