"""
Email Service using Resend API for RateRight
Handles all transactional emails for the platform
"""

import resend
from flask import current_app
import logging

logger = logging.getLogger(__name__)


def init_resend():
    """Initialize Resend with API key from config"""
    api_key = current_app.config.get('RESEND_API_KEY')
    if api_key:
        resend.api_key = api_key
        return True
    logger.warning("RESEND_API_KEY not configured. Email sending will be logged only.")
    return False


class EmailService:
    """Email service using Resend API"""
    
    @staticmethod
    def send_email(to_email, subject, body, html_body=None):
        """
        Send an email using Resend
        
        Args:
            to_email (str): Recipient email address
            subject (str): Email subject
            body (str): Plain text body
            html_body (str, optional): HTML content of the email
        
        Returns:
            bool: True if email sent successfully, False otherwise
        """
        if not init_resend():
            logger.info(f"[EMAIL WOULD BE SENT] To: {to_email}, Subject: {subject}")
            return False
        
        from_email = current_app.config.get('MAIL_FROM_EMAIL', 'noreply@rateright.com.au')
        from_name = current_app.config.get('MAIL_FROM_NAME', 'RateRight')
        
        try:
            params = {
                "from": f"{from_name} <{from_email}>",
                "to": [to_email],
                "subject": subject,
                "html": html_body if html_body else f"<html><body><pre>{body}</pre></body></html>",
            }
            
            response = resend.Emails.send(params)
            logger.info(f"Email sent successfully to {to_email}. ID: {response.get('id')}")
            return True
            
        except Exception as e:
            logger.error(f"Failed to send email to {to_email}: {str(e)}")
            return False
    
    @staticmethod
    def send_password_reset_email(to_email, reset_url, user_name=None):
        """
        Send password reset email with reset link
        
        Args:
            to_email (str): User's email address
            reset_url (str): Password reset URL
            user_name (str, optional): User's name for personalization
        
        Returns:
            bool: True if email sent successfully, False otherwise
        """
        if not init_resend():
            logger.info(f"[PASSWORD RESET EMAIL] To: {to_email}, URL: {reset_url}")
            return False
            
        subject = "Reset Your RateRight Password"
        
        cloudinary_cloud_name = current_app.config.get('CLOUDINARY_CLOUD_NAME', 'dcys6tfcf')
        logo_url = f'https://res.cloudinary.com/{cloudinary_cloud_name}/image/upload/f_png,w_400,q_auto/logo_black_i8fn48.png'
        
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #1e293b; background: #f8fafc; margin: 0; padding: 20px;">
            <div style="max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <div style="background: #ffffff; padding: 30px 40px 20px 40px; text-align: center; border-bottom: 1px solid #e2e8f0;">
                    <img src="{logo_url}" alt="RateRight" style="max-width: 200px; height: auto;">
                </div>
                
                <div style="padding: 40px;">
                    <h2 style="color: #1e293b; margin-top: 0; font-size: 24px; font-weight: 600;">Reset Your Password</h2>
                    
                    {"<p>Hi " + user_name + ",</p>" if user_name else "<p>Hi there,</p>"}
                    
                    <p>We received a request to reset your password for your RateRight account. Click the button below to create a new password:</p>
                    
                    <div style="text-align: center;">
                        <a href="{reset_url}" style="display: inline-block; background: #9acd32; color: #ffffff !important; padding: 14px 28px; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 20px 0;">Reset Password</a>
                    </div>
                    
                    <p>Or copy and paste this link into your browser:</p>
                    <p style="word-break: break-all; color: #9acd32; font-size: 14px;">{reset_url}</p>
                    
                    <div style="background: #fef3c7; border-left: 4px solid #f59e0b; padding: 12px; margin: 20px 0; font-size: 14px;">
                        <strong>⏰ This link will expire in 1 hour</strong> for security reasons.
                    </div>
                    
                    <p>If you didn't request a password reset, you can safely ignore this email. Your password will remain unchanged.</p>
                    
                    <div style="margin-top: 30px; padding: 15px 20px; background: #1e293b; color: #ffffff; border-radius: 6px; font-size: 12px; line-height: 1.6;">
                        <table style="width: 100%; border-collapse: collapse;">
                            <tr>
                                <td style="width: 50%; vertical-align: top; padding-right: 15px;">
                                    <strong style="font-size: 14px;">RateRight Pty Ltd</strong><br>
                                    ABN: 46 689 397 582<br>
                                    <a href="https://rateright.com.au" style="color: #9acd32; text-decoration: none;">rateright.com.au</a>
                                </td>
                                <td style="width: 50%; vertical-align: top; padding-left: 15px; border-left: 1px solid #475569; font-size: 11px; color: #cbd5e1;">
                                    RateRight acts as a platform facilitator only. Independent contractor relationships remain between hirers and workers.
                                </td>
                            </tr>
                        </table>
                    </div>
                    <p style="text-align: center; font-size: 11px; color: #64748b; margin-top: 15px;">This is an automated security message. Please do not reply.</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        return EmailService.send_email(to_email, subject, "", html_content)
    
    @staticmethod
    def send_verification_email(to_email, verification_url, user_name=None):
        """
        Send email verification email with verification link
        
        Args:
            to_email (str): User's email address
            verification_url (str): Email verification URL
            user_name (str, optional): User's name for personalization
        
        Returns:
            bool: True if email sent successfully, False otherwise
        """
        if not init_resend():
            logger.info(f"[EMAIL VERIFICATION] To: {to_email}, URL: {verification_url}")
            return False
            
        subject = "Verify Your RateRight Account"
        
        cloudinary_cloud_name = current_app.config.get('CLOUDINARY_CLOUD_NAME', 'dcys6tfcf')
        logo_url = f'https://res.cloudinary.com/{cloudinary_cloud_name}/image/upload/f_png,w_400,q_auto/logo_black_i8fn48.png'
        
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #1e293b; background: #f8fafc; margin: 0; padding: 20px;">
            <div style="max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <div style="background: #ffffff; padding: 30px 40px 20px 40px; text-align: center; border-bottom: 1px solid #e2e8f0;">
                    <img src="{logo_url}" alt="RateRight" style="max-width: 200px; height: auto;">
                </div>
                
                <div style="padding: 40px;">
                    <h2 style="color: #1e293b; margin-top: 0; font-size: 24px; font-weight: 600;">Welcome to RateRight!</h2>
                    
                    {"<p>Hi " + user_name + ",</p>" if user_name else "<p>Hi there,</p>"}
                    
                    <p>Thank you for registering with RateRight, Australia's trusted construction marketplace. To complete your registration, please verify your email address by clicking the button below:</p>
                    
                    <div style="text-align: center;">
                        <a href="{verification_url}" style="display: inline-block; background: #9acd32; color: #ffffff !important; padding: 14px 28px; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 20px 0;">Verify Email Address</a>
                    </div>
                    
                    <p>Or copy and paste this link into your browser:</p>
                    <p style="word-break: break-all; color: #9acd32; font-size: 14px;">{verification_url}</p>
                    
                    <div style="background: #dbeafe; border-left: 4px solid #9acd32; padding: 12px; margin: 20px 0; font-size: 14px;">
                        <strong>⏰ This verification link will expire in 24 hours</strong> for security reasons.
                    </div>
                    
                    <p>Once verified, you'll be able to log in and start using all RateRight features.</p>
                    
                    <p>If you didn't create an account with RateRight, you can safely ignore this email.</p>
                    
                    <div style="margin-top: 30px; padding: 15px 20px; background: #1e293b; color: #ffffff; border-radius: 6px; font-size: 12px; line-height: 1.6;">
                        <table style="width: 100%; border-collapse: collapse;">
                            <tr>
                                <td style="width: 50%; vertical-align: top; padding-right: 15px;">
                                    <strong style="font-size: 14px;">RateRight Pty Ltd</strong><br>
                                    ABN: 46 689 397 582<br>
                                    <a href="https://rateright.com.au" style="color: #9acd32; text-decoration: none;">rateright.com.au</a>
                                </td>
                                <td style="width: 50%; vertical-align: top; padding-left: 15px; border-left: 1px solid #475569; font-size: 11px; color: #cbd5e1;">
                                    RateRight acts as a platform facilitator only. Independent contractor relationships remain between hirers and workers.
                                </td>
                            </tr>
                        </table>
                    </div>
                    <p style="text-align: center; font-size: 11px; color: #64748b; margin-top: 15px;">This is an automated message. Please do not reply.</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        return EmailService.send_email(to_email, subject, "", html_content)
    
    @staticmethod
    def generate_standard_email_html(title, content, action_url=None, action_text="View Details", user_name=None, unsubscribe_url=None):
        """
        Generate standardized HTML email with RateRight branding
        
        Args:
            title (str): Email title/heading
            content (str): Main email content (can include HTML)
            action_url (str, optional): URL for call-to-action button
            action_text (str, optional): Text for CTA button (default: "View Details")
            user_name (str, optional): User's name for personalization
            unsubscribe_url (str, optional): Unsubscribe link URL
        
        Returns:
            str: Complete HTML email
        """
        cloudinary_cloud_name = current_app.config.get('CLOUDINARY_CLOUD_NAME', 'dcys6tfcf')
        logo_url = f'https://res.cloudinary.com/{cloudinary_cloud_name}/image/upload/f_png,w_400,q_auto/logo_black_i8fn48.png'
        
        # Build action button HTML if URL provided
        action_button_html = ""
        if action_url:
            action_button_html = f"""
            <div style="text-align: center; margin: 30px 0;">
                <a href="{action_url}" style="display: inline-block; background: #9acd32; color: #ffffff !important; padding: 14px 28px; text-decoration: none; border-radius: 6px; font-weight: 600;">{action_text}</a>
            </div>
            """
        
        # Build unsubscribe link if provided
        unsubscribe_html = ""
        if unsubscribe_url:
            unsubscribe_html = f'<br><a href="{unsubscribe_url}" style="color: #64748b; text-decoration: underline;">Unsubscribe from emails</a>'
        
        # Build greeting
        greeting_html = f"<p>Hi {user_name},</p>" if user_name else "<p>Hi there,</p>"
        
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #1e293b; background: #f8fafc; margin: 0; padding: 20px;">
            <div style="max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <div style="background: #ffffff; padding: 30px 40px 20px 40px; text-align: center; border-bottom: 1px solid #e2e8f0;">
                    <img src="{logo_url}" alt="RateRight" style="max-width: 200px; height: auto;">
                </div>
                
                <div style="padding: 40px;">
                    <h2 style="color: #1e293b; margin-top: 0; font-size: 24px; font-weight: 600;">{title}</h2>
                    
                    {greeting_html}
                    
                    {content}
                    
                    {action_button_html}
                    
                    <div style="margin-top: 30px; padding: 15px 20px; background: #1e293b; color: #ffffff; border-radius: 6px; font-size: 12px; line-height: 1.6;">
                        <table style="width: 100%; border-collapse: collapse;">
                            <tr>
                                <td style="width: 50%; vertical-align: top; padding-right: 15px;">
                                    <strong style="font-size: 14px;">RateRight Pty Ltd</strong><br>
                                    ABN: 46 689 397 582<br>
                                    <a href="https://rateright.com.au" style="color: #9acd32; text-decoration: none;">rateright.com.au</a>
                                </td>
                                <td style="width: 50%; vertical-align: top; padding-left: 15px; border-left: 1px solid #475569; font-size: 11px; color: #cbd5e1;">
                                    RateRight acts as a platform facilitator only. Independent contractor relationships remain between hirers and workers.
                                </td>
                            </tr>
                        </table>
                    </div>
                    <p style="text-align: center; font-size: 11px; color: #64748b; margin-top: 15px;">This is an automated message. Please do not reply.{unsubscribe_html}</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        return html_content
    
    @staticmethod
    def send_notification_email(user_email, notification_type, data):
        """Send notification emails"""
        logger.info(f"Notification email: {notification_type} to {user_email}")
        # Implement specific notification email templates as needed
        return True
    
    @staticmethod
    def send_booking_confirmation(booking):
        """Send booking confirmation emails"""
        logger.info(f"Booking confirmation for booking {booking.id if hasattr(booking, 'id') else 'N/A'}")
        return True
    
    @staticmethod
    def send_message_notification(message):
        """Send message notification emails"""
        logger.info(f"Message notification for message {message.id if hasattr(message, 'id') else 'N/A'}")
        return True

# Create singleton instance
email_service = EmailService()
