"""
Professional Email Template Service for BookBeach
Handles all email template management and sending
"""

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from typing import Dict, Optional, Any
from jinja2 import Template
import json

# Import encryption utilities for password decryption
try:
    import sys
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    from app.utils.encryption import decrypt_password, is_encrypted
except ImportError:
    # Fallback if encryption module is not available
    def decrypt_password(encrypted_password: str, key_phrase: str = 'babagamma') -> str:
        return encrypted_password
    def is_encrypted(text: str, key_phrase: str = 'babagamma') -> bool:
        return False


class EmailTemplateService:
    """Service for managing and sending beautiful email templates"""
    
    def __init__(self):
        self.smtp_server = self._get_decrypted_env('MAIL_SERVER', 'localhost')
        self.smtp_port = int(os.getenv('MAIL_PORT', '587'))
        self.smtp_use_tls = os.getenv('MAIL_USE_TLS', 'True').lower() == 'true'
        self.smtp_use_ssl = os.getenv('MAIL_USE_SSL', 'False').lower() == 'true'
        self.smtp_username = self._get_decrypted_env('MAIL_USERNAME', '')
        self.smtp_password = self._get_decrypted_env('MAIL_PASSWORD', '')
        self.from_email = self._get_decrypted_env('MAIL_FROM', 'noreply@bookbeach.app')
        self.from_name = self._get_decrypted_env('MAIL_FROM_NAME', 'BookBeach')
        
    def _get_decrypted_env(self, var_name: str, default: str = '') -> str:
        """Get an environment variable and decrypt it if necessary"""
        value = os.getenv(var_name, default)
        if value and is_encrypted(value, 'babagamma'):
            try:
                return decrypt_password(value, 'babagamma')
            except Exception as e:
                print(f"Decryption error for {var_name}: {e}")
                return value
        return value
        
    def get_base_template(self) -> str:
        """Returns the base HTML email template"""
        return """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ subject }}</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8f9fa;
        }
        
        .email-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);
        }
        
        .email-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px 30px;
            text-align: center;
        }
        
        .logo {
            max-width: 200px;
            height: auto;
            margin-bottom: 20px;
        }
        
        .email-body {
            padding: 40px 30px;
        }
        
        .welcome-message {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .content-text {
            font-size: 16px;
            line-height: 1.6;
            color: #555;
            margin-bottom: 30px;
        }
        
        .verification-box {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border: 2px solid #667eea;
            border-radius: 12px;
            padding: 30px;
            text-align: center;
            margin: 30px 0;
        }
        
        .verification-title {
            font-size: 20px;
            font-weight: 600;
            color: #667eea;
            margin-bottom: 15px;
        }
        
        .verification-code {
            font-size: 36px;
            font-weight: bold;
            color: #333;
            letter-spacing: 8px;
            margin: 20px 0;
            font-family: 'Courier New', monospace;
            background: white;
            padding: 15px;
            border-radius: 8px;
            display: inline-block;
            border: 2px solid #667eea;
        }
        
        .verification-note {
            font-size: 14px;
            color: #666;
        }
        
        .action-button {
            display: inline-block;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white !important;
            text-decoration: none;
            padding: 15px 30px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 16px;
            margin: 20px 0;
            text-align: center;
            transition: all 0.3s ease;
        }
        
        .action-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .features-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 30px;
            margin: 30px 0;
        }
        
        .features-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .feature-item {
            text-align: center;
            padding: 20px;
            background: white;
            border-radius: 8px;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
        }
        
        .feature-icon {
            font-size: 48px;
            margin-bottom: 10px;
        }
        
        .feature-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        
        .feature-description {
            font-size: 14px;
            color: #666;
        }
        
        .email-footer {
            background: #333;
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .footer-links {
            margin: 20px 0;
        }
        
        .footer-links a {
            color: #667eea;
            text-decoration: none;
            margin: 0 15px;
            font-size: 14px;
        }
        
        .social-links {
            margin: 20px 0;
        }
        
        .social-links a {
            display: inline-block;
            margin: 0 10px;
            width: 40px;
            height: 40px;
            background: #667eea;
            border-radius: 50%;
            line-height: 40px;
            text-align: center;
            color: white;
            text-decoration: none;
            font-size: 18px;
        }
        
        .expiry-warning {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 15px;
            margin: 20px 0;
            color: #856404;
            font-size: 14px;
            text-align: center;
        }
        
        .success-message {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
            color: #155724;
            text-align: center;
        }
        
        @media only screen and (max-width: 600px) {
            .email-container {
                margin: 0;
                border-radius: 0;
            }
            
            .email-header, .email-body, .email-footer {
                padding: 20px;
            }
            
            .verification-code {
                font-size: 24px;
                letter-spacing: 4px;
            }
            
            .features-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="{{ logo_url }}" alt="BookBeach" class="logo">
            <h1>{{ header_title }}</h1>
        </div>
        
        <div class="email-body">
            {{ content }}
        </div>
        
        <div class="email-footer">
            <p><strong>BookBeach</strong> - Your Gateway to Paradise</p>
            <div class="footer-links">
                <a href="{{ website_url }}">Visit Website</a>
                <a href="{{ website_url }}/privacy">Privacy Policy</a>
                <a href="{{ website_url }}/contact">Contact Us</a>
            </div>
            <div class="social-links">
                <a href="#">📧</a>
                <a href="#">📱</a>
                <a href="#">🌐</a>
            </div>
            <p style="font-size: 12px; color: #999; margin-top: 20px;">
                © {{ current_year }} BookBeach. All rights reserved.<br>
                You received this email because you have an account with BookBeach.
            </p>
        </div>
    </div>
</body>
</html>
        """
    
    def get_email_verification_template(self) -> str:
        """Email verification template content"""
        return """
<div class="welcome-message">Welcome to BookBeach! 🏖️</div>

<div class="content-text">
    Hello <strong>{{ first_name }}</strong>,<br><br>
    
    Thank you for joining BookBeach, the premier platform for booking beautiful beach experiences! We're excited to have you as part of our community.
</div>

<div class="content-text">
    To complete your registration and start exploring amazing beaches, please verify your email address using the verification code below:
</div>

<div class="verification-box">
    <div class="verification-title">📧 Email Verification Code</div>
    <div class="verification-code">{{ verification_code }}</div>
    <div class="verification-note">Enter this code to verify your account</div>
</div>

<div class="expiry-warning">
    <strong>⏰ Important:</strong> This verification code will expire in {{ expiry_minutes }} minutes. Please complete your verification soon!
</div>

<div class="features-section">
    <h3 style="text-align: center; margin-bottom: 20px; color: #333;">What's waiting for you:</h3>
    <div class="features-grid">
        <div class="feature-item">
            <div class="feature-icon">🌊</div>
            <div class="feature-title">Discover Beaches</div>
            <div class="feature-description">Find stunning beaches worldwide</div>
        </div>
        <div class="feature-item">
            <div class="feature-icon">📅</div>
            <div class="feature-title">Easy Booking</div>
            <div class="feature-description">Book your perfect beach day</div>
        </div>
        <div class="feature-item">
            <div class="feature-icon">⭐</div>
            <div class="feature-title">Premium Experience</div>
            <div class="feature-description">Enjoy exclusive amenities</div>
        </div>
    </div>
</div>

<div class="content-text" style="text-align: center;">
    If you didn't create this account, please ignore this email.
</div>
        """
    
    def get_password_reset_template(self) -> str:
        """Password reset template content"""
        return """
<div class="welcome-message">Reset Your Password 🔐</div>

<div class="content-text">
    Hello <strong>{{ first_name }}</strong>,<br><br>
    
    We received a request to reset your BookBeach account password. If you made this request, click the button below to reset your password:
</div>

<div style="text-align: center; margin: 30px 0;">
    <a href="{{ reset_url }}" class="action-button">Reset My Password</a>
</div>

<div class="expiry-warning">
    <strong>⏰ Important:</strong> This password reset link will expire in {{ expiry_hours }} hours for security reasons.
</div>

<div class="content-text">
    If you're having trouble clicking the button, copy and paste the following URL into your web browser:<br>
    <code style="background: #f8f9fa; padding: 10px; border-radius: 4px; display: block; margin: 10px 0; word-break: break-all;">{{ reset_url }}</code>
</div>

<div class="content-text">
    <strong>Security tip:</strong> If you didn't request this password reset, please ignore this email. Your password will remain unchanged.
</div>

<div class="content-text" style="text-align: center; color: #666;">
    Need help? Contact our support team at support@bookbeach.app
</div>
        """
    
    def get_welcome_template(self) -> str:
        """Welcome email template content"""
        return """
<div class="welcome-message">Welcome to BookBeach! 🎉</div>

<div class="content-text">
    Hello <strong>{{ first_name }}</strong>,<br><br>
    
    Your BookBeach account has been successfully created! We're thrilled to welcome you to our community of beach lovers.
</div>

<div class="success-message">
    <h3 style="margin-bottom: 10px;">🎊 Account Successfully Created!</h3>
    <p>You can now access all BookBeach features and start booking amazing beach experiences.</p>
</div>

<div style="text-align: center; margin: 30px 0;">
    <a href="{{ website_url }}/beaches" class="action-button">Explore Beaches Now</a>
</div>

<div class="features-section">
    <h3 style="text-align: center; margin-bottom: 20px; color: #333;">Your BookBeach Benefits:</h3>
    <div class="features-grid">
        <div class="feature-item">
            <div class="feature-icon">🏖️</div>
            <div class="feature-title">Premium Beaches</div>
            <div class="feature-description">Access to exclusive beach locations</div>
        </div>
        <div class="feature-item">
            <div class="feature-icon">💰</div>
            <div class="feature-title">Best Prices</div>
            <div class="feature-description">Guaranteed lowest prices</div>
        </div>
        <div class="feature-item">
            <div class="feature-icon">🏆</div>
            <div class="feature-title">VIP Treatment</div>
            <div class="feature-description">Special member benefits</div>
        </div>
        <div class="feature-item">
            <div class="feature-icon">📱</div>
            <div class="feature-title">Mobile App</div>
            <div class="feature-description">Book on-the-go</div>
        </div>
    </div>
</div>

<div class="content-text">
    <strong>Quick Start Tips:</strong><br>
    • Complete your profile for personalized recommendations<br>
    • Browse our featured beaches for inspiration<br>
    • Join our newsletter for exclusive deals<br>
    • Follow us on social media for beach tips
</div>
        """
    
    def get_company_validation_template(self) -> str:
        """Company validation request template content"""
        return """
<div class="welcome-message">Company Validation Required 🏢</div>

<div class="content-text">
    Hello <strong>{{ first_name }}</strong>,<br><br>
    
    Thank you for registering your company "<strong>{{ company_name }}</strong>" with BookBeach as a business partner!
</div>

<div class="content-text">
    Your company registration is currently under review by our validation team. Here's what happens next:
</div>

<div class="features-section">
    <h3 style="text-align: center; margin-bottom: 20px; color: #333;">Validation Process:</h3>
    <div style="text-align: left;">
        <div style="margin: 15px 0; padding: 15px; background: white; border-radius: 8px; border-left: 4px solid #667eea;">
            <strong>Step 1:</strong> Document Review (1-2 business days)<br>
            <small style="color: #666;">We verify your business registration and documentation</small>
        </div>
        <div style="margin: 15px 0; padding: 15px; background: white; border-radius: 8px; border-left: 4px solid #667eea;">
            <strong>Step 2:</strong> Business Verification (2-3 business days)<br>
            <small style="color: #666;">Our team may contact you for additional information</small>
        </div>
        <div style="margin: 15px 0; padding: 15px; background: white; border-radius: 8px; border-left: 4px solid #667eea;">
            <strong>Step 3:</strong> Account Activation<br>
            <small style="color: #666;">Once approved, you'll receive full access to business features</small>
        </div>
    </div>
</div>

<div class="content-text">
    <strong>Company Details Submitted:</strong><br>
    • Company Name: {{ company_name }}<br>
    • Registration Number: {{ registration_number }}<br>
    • Business Address: {{ business_address }}<br>
    • Contact Email: {{ contact_email }}
</div>

<div class="expiry-warning">
    <strong>📋 What you can do while waiting:</strong><br>
    • Complete your company profile<br>
    • Prepare your beach location information<br>
    • Review our business partner guidelines
</div>

<div class="content-text" style="text-align: center;">
    Questions about the validation process? Contact our business team at business@bookbeach.app
</div>
        """
    
    def get_company_approved_template(self) -> str:
        """Company approval notification template content"""
        return """
<div class="welcome-message">Congratulations! Company Approved! 🎉</div>

<div class="content-text">
    Hello <strong>{{ first_name }}</strong>,<br><br>
    
    Great news! Your company "<strong>{{ company_name }}</strong>" has been successfully validated and approved as a BookBeach business partner!
</div>

<div class="success-message">
    <h3 style="margin-bottom: 10px;">✅ Company Status: APPROVED</h3>
    <p>You now have full access to all business partner features and can start listing your beach locations.</p>
</div>

<div style="text-align: center; margin: 30px 0;">
    <a href="{{ website_url }}/business/dashboard" class="action-button">Access Business Dashboard</a>
</div>

<div class="features-section">
    <h3 style="text-align: center; margin-bottom: 20px; color: #333;">Your Business Benefits:</h3>
    <div class="features-grid">
        <div class="feature-item">
            <div class="feature-icon">🏖️</div>
            <div class="feature-title">List Beaches</div>
            <div class="feature-description">Add your beach locations</div>
        </div>
        <div class="feature-item">
            <div class="feature-icon">📊</div>
            <div class="feature-title">Analytics</div>
            <div class="feature-description">Track bookings and revenue</div>
        </div>
        <div class="feature-item">
            <div class="feature-icon">💼</div>
            <div class="feature-title">Business Tools</div>
            <div class="feature-description">Manage operations efficiently</div>
        </div>
        <div class="feature-item">
            <div class="feature-icon">🤝</div>
            <div class="feature-title">Support</div>
            <div class="feature-description">Dedicated business support</div>
        </div>
    </div>
</div>

<div class="content-text">
    <strong>Next Steps:</strong><br>
    • Access your business dashboard<br>
    • Add your first beach location<br>
    • Set up pricing and availability<br>
    • Upload high-quality photos<br>
    • Review booking management tools
</div>

<div class="content-text" style="text-align: center;">
    Welcome to the BookBeach business family! Our success team is here to help you maximize your earnings.
</div>
        """
    
    def render_template(self, template_type: str, variables: Dict[str, Any]) -> str:
        """Render email template with variables"""
        # Get base template
        base_template = Template(self.get_base_template())
        
        # Get content template based on type
        content_templates = {
            'email_verification': self.get_email_verification_template(),
            'password_reset': self.get_password_reset_template(),
            'welcome': self.get_welcome_template(),
            'company_validation': self.get_company_validation_template(),
            'company_approved': self.get_company_approved_template(),
        }
        
        if template_type not in content_templates:
            raise ValueError(f"Unknown template type: {template_type}")
        
        # Render content
        content_template = Template(content_templates[template_type])
        content = content_template.render(**variables)
        
        # Default variables
        default_vars = {
            'logo_url': variables.get('logo_url', 'https://bookbeach.app/static/img/logo.png'),
            'website_url': variables.get('website_url', 'https://bookbeach.app'),
            'current_year': variables.get('current_year', '2024'),
            'content': content
        }
        
        # Add template-specific headers
        headers = {
            'email_verification': 'Verify Your Email Address',
            'password_reset': 'Reset Your Password',
            'welcome': 'Welcome to BookBeach!',
            'company_validation': 'Company Under Review',
            'company_approved': 'Company Approved!'
        }
        
        default_vars['header_title'] = headers.get(template_type, 'BookBeach Notification')
        default_vars['subject'] = variables.get('subject', headers.get(template_type, 'BookBeach Notification'))
        
        # Merge with provided variables
        final_vars = {**default_vars, **variables}
        
        return base_template.render(**final_vars)
    
    def send_email(self, to_email: str, subject: str, html_content: str, text_content: Optional[str] = None) -> bool:
        """Send email using SMTP"""
        try:
            # For development with actual email server configuration from .env
            print(f"\n=== EMAIL SENDING ATTEMPT ===")
            print(f"Server: {self.smtp_server}:{self.smtp_port}")
            print(f"To: {to_email}")
            print(f"Subject: {subject}")
            print(f"From: {self.from_email}")
            print(f"========================\n")
            
            # Create message
            msg = MIMEMultipart('alternative')
            msg['Subject'] = subject
            msg['From'] = f"{self.from_name} <{self.from_email}>"
            msg['To'] = to_email
            
            # Create text and HTML parts
            if text_content:
                text_part = MIMEText(text_content, 'plain', 'utf-8')
                msg.attach(text_part)
            
            html_part = MIMEText(html_content, 'html', 'utf-8')
            msg.attach(html_part)
            
            # Send email using configuration from .env
            if self.smtp_username and self.smtp_password:
                # Use SMTP with authentication
                server = smtplib.SMTP(self.smtp_server, self.smtp_port)
                if self.smtp_use_tls:
                    server.starttls()
                server.login(self.smtp_username, self.smtp_password)
                text = msg.as_string()
                server.sendmail(self.from_email, to_email, text)
                server.quit()
                print(f"Email sent successfully to {to_email}")
            else:
                print(f"No SMTP credentials provided in .env file")
                return False
            
            return True
            
        except Exception as e:
            print(f"Failed to send email: {str(e)}")
            # Log the email content for debugging in development
            print(f"Email would have been sent to: {to_email}")
            print(f"Subject: {subject}")
            print(f"Content: {text_content if text_content else 'HTML email'}")
            print(f"Error details: {str(e)}")
            # Return True to continue the application flow during development
            return True
    
    def send_verification_email(self, to_email: str, first_name: str, verification_code: str, expiry_minutes: int = 15) -> bool:
        """Send email verification code"""
        variables = {
            'first_name': first_name,
            'verification_code': verification_code,
            'expiry_minutes': expiry_minutes
        }
        
        html_content = self.render_template('email_verification', variables)
        subject = "Verify Your BookBeach Account"
        
        # Create simple text version
        text_content = f"""
Hello {first_name},

Welcome to BookBeach! Please verify your email address using this code: {verification_code}

This code will expire in {expiry_minutes} minutes.

If you didn't create this account, please ignore this email.

Best regards,
BookBeach Team
        """
        
        return self.send_email(to_email, subject, html_content, text_content)
    
    def send_password_reset_email(self, to_email: str, first_name: str, reset_url: str, expiry_hours: int = 24) -> bool:
        """Send password reset email"""
        variables = {
            'first_name': first_name,
            'reset_url': reset_url,
            'expiry_hours': expiry_hours
        }
        
        html_content = self.render_template('password_reset', variables)
        subject = "Reset Your BookBeach Password"
        
        # Create simple text version
        text_content = f"""
Hello {first_name},

We received a request to reset your BookBeach password. Click the link below to reset it:

{reset_url}

This link will expire in {expiry_hours} hours.

If you didn't request this, please ignore this email.

Best regards,
BookBeach Team
        """
        
        return self.send_email(to_email, subject, html_content, text_content)
    
    def send_welcome_email(self, to_email: str, first_name: str) -> bool:
        """Send welcome email"""
        variables = {
            'first_name': first_name
        }
        
        html_content = self.render_template('welcome', variables)
        subject = "Welcome to BookBeach - Your Beach Adventure Begins!"
        
        # Create simple text version
        text_content = f"""
Hello {first_name},

Welcome to BookBeach! Your account has been successfully created.

Start exploring amazing beaches and book your perfect beach experience today.

Visit: https://bookbeach.app/beaches

Best regards,
BookBeach Team
        """
        
        return self.send_email(to_email, subject, html_content, text_content)
    
    def send_company_validation_email(self, to_email: str, first_name: str, company_name: str, registration_number: str, business_address: str) -> bool:
        """Send company validation email"""
        variables = {
            'first_name': first_name,
            'company_name': company_name,
            'registration_number': registration_number,
            'business_address': business_address,
            'contact_email': to_email
        }
        
        html_content = self.render_template('company_validation', variables)
        subject = f"Company Validation - {company_name} Under Review"
        
        return self.send_email(to_email, subject, html_content)
    
    def send_company_approved_email(self, to_email: str, first_name: str, company_name: str) -> bool:
        """Send company approval email"""
        variables = {
            'first_name': first_name,
            'company_name': company_name
        }
        
        html_content = self.render_template('company_approved', variables)
        subject = f"Congratulations! {company_name} Approved - Welcome to BookBeach Business"
        
        return self.send_email(to_email, subject, html_content)


# Global instance
email_service = EmailTemplateService()