"""
Email Templates
Comprehensive HTML email templates for all transactional emails
"""
from datetime import datetime
from typing import Dict, Any, List, Optional


class EmailTemplates:
    """
    Professional email templates for AI360 Solutions
    All templates are responsive and follow email best practices
    """

    # Base styles used across all templates
    BASE_STYLES = """
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #1f2937;
            margin: 0;
            padding: 0;
            background-color: #f3f4f6;
            -webkit-font-smoothing: antialiased;
        }
        .wrapper {
            width: 100%;
            background-color: #f3f4f6;
            padding: 40px 20px;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            background: #ffffff;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }
        .header {
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            padding: 40px 30px;
            text-align: center;
        }
        .header-icon {
            font-size: 48px;
            margin-bottom: 15px;
        }
        .header h1 {
            color: white;
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            letter-spacing: -0.5px;
        }
        .header p {
            color: rgba(255,255,255,0.9);
            margin: 10px 0 0 0;
            font-size: 16px;
        }
        .content {
            padding: 40px 30px;
        }
        .content p {
            margin: 0 0 16px 0;
            color: #4b5563;
        }
        .button-container {
            text-align: center;
            margin: 30px 0;
        }
        .button {
            display: inline-block;
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white !important;
            padding: 16px 48px;
            text-decoration: none;
            border-radius: 10px;
            font-weight: 600;
            font-size: 16px;
            box-shadow: 0 4px 14px 0 rgba(59, 130, 246, 0.4);
            transition: all 0.2s ease;
        }
        .button-secondary {
            background: #10b981;
            box-shadow: 0 4px 14px 0 rgba(16, 185, 129, 0.4);
        }
        .button-danger {
            background: #ef4444;
            box-shadow: 0 4px 14px 0 rgba(239, 68, 68, 0.4);
        }
        .info-box {
            background: #f0f9ff;
            border: 1px solid #bae6fd;
            border-left: 4px solid #0ea5e9;
            padding: 16px 20px;
            border-radius: 8px;
            margin: 24px 0;
        }
        .warning-box {
            background: #fffbeb;
            border: 1px solid #fcd34d;
            border-left: 4px solid #f59e0b;
            padding: 16px 20px;
            border-radius: 8px;
            margin: 24px 0;
        }
        .success-box {
            background: #ecfdf5;
            border: 1px solid #6ee7b7;
            border-left: 4px solid #10b981;
            padding: 16px 20px;
            border-radius: 8px;
            margin: 24px 0;
        }
        .danger-box {
            background: #fef2f2;
            border: 1px solid #fecaca;
            border-left: 4px solid #ef4444;
            padding: 16px 20px;
            border-radius: 8px;
            margin: 24px 0;
        }
        .divider {
            border: none;
            border-top: 1px solid #e5e7eb;
            margin: 30px 0;
        }
        .footer {
            background: #f9fafb;
            text-align: center;
            padding: 30px;
            border-top: 1px solid #e5e7eb;
        }
        .footer p {
            margin: 8px 0;
            color: #6b7280;
            font-size: 13px;
        }
        .footer a {
            color: #3b82f6;
            text-decoration: none;
        }
        .social-links {
            margin: 20px 0;
        }
        .social-links a {
            display: inline-block;
            margin: 0 8px;
            color: #6b7280;
        }
        .table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        .table th, .table td {
            padding: 12px 16px;
            text-align: left;
            border-bottom: 1px solid #e5e7eb;
        }
        .table th {
            background: #f9fafb;
            font-weight: 600;
            color: #374151;
        }
        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        .badge-success { background: #d1fae5; color: #065f46; }
        .badge-warning { background: #fef3c7; color: #92400e; }
        .badge-danger { background: #fee2e2; color: #991b1b; }
        .badge-info { background: #dbeafe; color: #1e40af; }
        .feature-list {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }
        .feature-list li {
            padding: 12px 0;
            border-bottom: 1px solid #f3f4f6;
            display: flex;
            align-items: center;
        }
        .feature-list li:last-child {
            border-bottom: none;
        }
        .feature-icon {
            width: 24px;
            height: 24px;
            background: #dbeafe;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            color: #3b82f6;
        }
        .stats-grid {
            display: table;
            width: 100%;
            margin: 20px 0;
        }
        .stat-item {
            display: table-cell;
            text-align: center;
            padding: 20px;
            background: #f9fafb;
            border-radius: 8px;
        }
        .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: #3b82f6;
        }
        .stat-label {
            font-size: 13px;
            color: #6b7280;
            margin-top: 4px;
        }
    """

    @classmethod
    def _base_template(cls, content: str, preheader: str = "") -> str:
        """Wrap content in base HTML template"""
        return f"""
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <title>AI360 Solutions</title>
            <!--[if mso]>
            <style type="text/css">
                body, table, td {{font-family: Arial, Helvetica, sans-serif !important;}}
            </style>
            <![endif]-->
            <style>
                {cls.BASE_STYLES}
            </style>
        </head>
        <body>
            <!-- Preheader text (shows in email preview) -->
            <div style="display:none;font-size:1px;color:#ffffff;line-height:1px;max-height:0px;max-width:0px;opacity:0;overflow:hidden;">
                {preheader}
            </div>
            <div class="wrapper">
                {content}
            </div>
        </body>
        </html>
        """

    # ============================================================
    # WELCOME EMAILS
    # ============================================================

    @classmethod
    def welcome_new_user(cls, context: Dict[str, Any]) -> str:
        """Welcome email for new user registration"""
        user_name = context.get('user_name', 'there')
        dashboard_url = context.get('dashboard_url', '#')
        trial_days = context.get('trial_days', 14)
        year = context.get('year', datetime.now().year)

        content = f"""
        <div class="container">
            <div class="header">
                <div class="header-icon">🎉</div>
                <h1>Welcome to AI360!</h1>
                <p>Your AI-powered business transformation starts now</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p>Welcome to AI360 Solutions! We're thrilled to have you join our community of forward-thinking businesses leveraging AI to transform customer engagement.</p>

                <div class="success-box">
                    <strong>🎁 Your {trial_days}-day free trial has started!</strong><br>
                    Explore all premium features with no commitment.
                </div>

                <p><strong>Here's what you can do with AI360:</strong></p>

                <ul class="feature-list">
                    <li>
                        <span class="feature-icon">💬</span>
                        <span><strong>AI Chatbots</strong> - Deploy intelligent chatbots on your website</span>
                    </li>
                    <li>
                        <span class="feature-icon">📱</span>
                        <span><strong>WhatsApp Integration</strong> - Connect with customers on their favorite platform</span>
                    </li>
                    <li>
                        <span class="feature-icon">📊</span>
                        <span><strong>Analytics Dashboard</strong> - Get insights into customer interactions</span>
                    </li>
                    <li>
                        <span class="feature-icon">🔧</span>
                        <span><strong>Easy Customization</strong> - Match your brand perfectly</span>
                    </li>
                </ul>

                <div class="button-container">
                    <a href="{dashboard_url}" class="button">Go to Dashboard →</a>
                </div>

                <hr class="divider">

                <p style="color: #6b7280; font-size: 14px;">Need help getting started? Our support team is here for you at <a href="mailto:support@ai360.com">support@ai360.com</a></p>

                <p>Best regards,<br><strong>The AI360 Team</strong></p>
            </div>
            <div class="footer">
                <div class="social-links">
                    <a href="#">Twitter</a> • <a href="#">LinkedIn</a> • <a href="#">Facebook</a>
                </div>
                <p><a href="#">Privacy Policy</a> • <a href="#">Terms of Service</a> • <a href="#">Unsubscribe</a></p>
                <p>© {year} AI360 Solutions. All rights reserved.</p>
                <p style="color: #9ca3af;">Mumbai, India</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"Welcome {user_name}! Your {trial_days}-day free trial has started.")

    @classmethod
    def welcome_team_member(cls, context: Dict[str, Any]) -> str:
        """Welcome email for team member invited to organization"""
        user_name = context.get('user_name', 'there')
        inviter_name = context.get('inviter_name', 'Your colleague')
        company_name = context.get('company_name', 'the team')
        dashboard_url = context.get('dashboard_url', '#')
        role = context.get('role', 'team member')
        year = context.get('year', datetime.now().year)

        content = f"""
        <div class="container">
            <div class="header">
                <div class="header-icon">👋</div>
                <h1>You've Been Invited!</h1>
                <p>Join {company_name} on AI360</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p><strong>{inviter_name}</strong> has invited you to join <strong>{company_name}</strong> on AI360 Solutions as a <span class="badge badge-info">{role}</span>.</p>

                <div class="info-box">
                    <strong>What is AI360?</strong><br>
                    AI360 is an enterprise platform for AI-powered customer engagement, including intelligent chatbots, WhatsApp integration, and analytics.
                </div>

                <p>Click the button below to accept the invitation and set up your account:</p>

                <div class="button-container">
                    <a href="{dashboard_url}" class="button">Accept Invitation →</a>
                </div>

                <hr class="divider">

                <p style="color: #6b7280; font-size: 14px;">This invitation will expire in 7 days. If you didn't expect this invitation, you can safely ignore this email.</p>

                <p>Best regards,<br><strong>The AI360 Team</strong></p>
            </div>
            <div class="footer">
                <p>© {year} AI360 Solutions. All rights reserved.</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"{inviter_name} has invited you to join {company_name} on AI360")

    # ============================================================
    # INVOICE EMAILS
    # ============================================================

    @classmethod
    def invoice_created(cls, context: Dict[str, Any]) -> str:
        """Invoice created/sent email"""
        user_name = context.get('user_name', 'there')
        invoice_number = context.get('invoice_number', 'INV-0000')
        amount = context.get('amount', 0)
        currency = context.get('currency', 'INR')
        currency_symbol = '₹' if currency == 'INR' else '$'
        due_date = context.get('due_date', 'N/A')
        billing_period = context.get('billing_period', 'this month')
        plan_name = context.get('plan_name', 'Standard')
        invoice_url = context.get('invoice_url', '#')
        pay_url = context.get('pay_url', '#')
        line_items = context.get('line_items', [])
        tax_amount = context.get('tax_amount', 0)
        total_amount = context.get('total_amount', amount)
        year = context.get('year', datetime.now().year)

        # Build line items table
        items_html = ""
        if line_items:
            items_html = """
            <table class="table">
                <thead>
                    <tr>
                        <th>Description</th>
                        <th style="text-align: right;">Amount</th>
                    </tr>
                </thead>
                <tbody>
            """
            for item in line_items:
                items_html += f"""
                    <tr>
                        <td>{item.get('description', '')}</td>
                        <td style="text-align: right;">{currency_symbol}{item.get('amount', 0):,.2f}</td>
                    </tr>
                """
            items_html += f"""
                    <tr>
                        <td><strong>Subtotal</strong></td>
                        <td style="text-align: right;"><strong>{currency_symbol}{amount:,.2f}</strong></td>
                    </tr>
                    <tr>
                        <td>Tax (GST 18%)</td>
                        <td style="text-align: right;">{currency_symbol}{tax_amount:,.2f}</td>
                    </tr>
                    <tr style="background: #f0f9ff;">
                        <td><strong>Total</strong></td>
                        <td style="text-align: right;"><strong style="font-size: 18px; color: #3b82f6;">{currency_symbol}{total_amount:,.2f}</strong></td>
                    </tr>
                </tbody>
            </table>
            """

        content = f"""
        <div class="container">
            <div class="header" style="background: linear-gradient(135deg, #1f2937 0%, #374151 100%);">
                <div class="header-icon">📄</div>
                <h1>Invoice {invoice_number}</h1>
                <p>For {billing_period}</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p>Your invoice for the <strong>{plan_name}</strong> plan is ready. Here are the details:</p>

                <div style="background: #f9fafb; border-radius: 12px; padding: 24px; margin: 24px 0;">
                    <table style="width: 100%;">
                        <tr>
                            <td style="padding: 8px 0;">
                                <span style="color: #6b7280;">Invoice Number</span><br>
                                <strong>{invoice_number}</strong>
                            </td>
                            <td style="padding: 8px 0; text-align: right;">
                                <span style="color: #6b7280;">Due Date</span><br>
                                <strong>{due_date}</strong>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0;">
                                <span style="color: #6b7280;">Billing Period</span><br>
                                <strong>{billing_period}</strong>
                            </td>
                            <td style="padding: 8px 0; text-align: right;">
                                <span style="color: #6b7280;">Amount Due</span><br>
                                <strong style="font-size: 24px; color: #3b82f6;">{currency_symbol}{total_amount:,.2f}</strong>
                            </td>
                        </tr>
                    </table>
                </div>

                {items_html}

                <div class="button-container">
                    <a href="{pay_url}" class="button">Pay Now →</a>
                    <br><br>
                    <a href="{invoice_url}" style="color: #3b82f6; text-decoration: none;">View Full Invoice</a>
                </div>

                <div class="info-box">
                    <strong>💳 Payment Methods</strong><br>
                    We accept Credit/Debit Cards, UPI, Net Banking, and Bank Transfer.
                </div>

                <hr class="divider">

                <p style="color: #6b7280; font-size: 14px;">Questions about your invoice? Contact our billing team at <a href="mailto:billing@ai360.com">billing@ai360.com</a></p>

                <p>Best regards,<br><strong>AI360 Solutions Billing Team</strong></p>
            </div>
            <div class="footer">
                <p>© {year} AI360 Solutions. All rights reserved.</p>
                <p style="color: #9ca3af;">GSTIN: 27XXXXX1234X1ZX</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"Invoice {invoice_number} for {currency_symbol}{total_amount:,.2f} is ready")

    @classmethod
    def invoice_paid(cls, context: Dict[str, Any]) -> str:
        """Payment confirmation email"""
        user_name = context.get('user_name', 'there')
        invoice_number = context.get('invoice_number', 'INV-0000')
        amount = context.get('amount', 0)
        currency = context.get('currency', 'INR')
        currency_symbol = '₹' if currency == 'INR' else '$'
        payment_method = context.get('payment_method', 'Card')
        transaction_id = context.get('transaction_id', 'N/A')
        receipt_url = context.get('receipt_url', '#')
        next_billing_date = context.get('next_billing_date', 'N/A')
        year = context.get('year', datetime.now().year)

        content = f"""
        <div class="container">
            <div class="header" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                <div class="header-icon">✅</div>
                <h1>Payment Successful!</h1>
                <p>Thank you for your payment</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p>We've received your payment. Thank you for your continued trust in AI360!</p>

                <div class="success-box">
                    <strong>Payment Confirmed</strong><br>
                    Your payment of <strong>{currency_symbol}{amount:,.2f}</strong> has been processed successfully.
                </div>

                <div style="background: #f9fafb; border-radius: 12px; padding: 24px; margin: 24px 0;">
                    <table style="width: 100%;">
                        <tr>
                            <td style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                <span style="color: #6b7280;">Invoice Number</span>
                            </td>
                            <td style="padding: 8px 0; text-align: right; border-bottom: 1px solid #e5e7eb;">
                                <strong>{invoice_number}</strong>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                <span style="color: #6b7280;">Amount Paid</span>
                            </td>
                            <td style="padding: 8px 0; text-align: right; border-bottom: 1px solid #e5e7eb;">
                                <strong>{currency_symbol}{amount:,.2f}</strong>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                <span style="color: #6b7280;">Payment Method</span>
                            </td>
                            <td style="padding: 8px 0; text-align: right; border-bottom: 1px solid #e5e7eb;">
                                <strong>{payment_method}</strong>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                <span style="color: #6b7280;">Transaction ID</span>
                            </td>
                            <td style="padding: 8px 0; text-align: right; border-bottom: 1px solid #e5e7eb;">
                                <code style="background: #f3f4f6; padding: 2px 8px; border-radius: 4px;">{transaction_id}</code>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0;">
                                <span style="color: #6b7280;">Next Billing Date</span>
                            </td>
                            <td style="padding: 8px 0; text-align: right;">
                                <strong>{next_billing_date}</strong>
                            </td>
                        </tr>
                    </table>
                </div>

                <div class="button-container">
                    <a href="{receipt_url}" class="button button-secondary">Download Receipt →</a>
                </div>

                <hr class="divider">

                <p style="color: #6b7280; font-size: 14px;">This email serves as your payment confirmation. Keep it for your records.</p>

                <p>Best regards,<br><strong>AI360 Solutions Billing Team</strong></p>
            </div>
            <div class="footer">
                <p>© {year} AI360 Solutions. All rights reserved.</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"Payment of {currency_symbol}{amount:,.2f} confirmed for invoice {invoice_number}")

    @classmethod
    def invoice_overdue(cls, context: Dict[str, Any]) -> str:
        """Invoice overdue reminder"""
        user_name = context.get('user_name', 'there')
        invoice_number = context.get('invoice_number', 'INV-0000')
        amount = context.get('amount', 0)
        currency = context.get('currency', 'INR')
        currency_symbol = '₹' if currency == 'INR' else '$'
        days_overdue = context.get('days_overdue', 1)
        due_date = context.get('due_date', 'N/A')
        pay_url = context.get('pay_url', '#')
        year = context.get('year', datetime.now().year)

        content = f"""
        <div class="container">
            <div class="header" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                <div class="header-icon">⚠️</div>
                <h1>Payment Overdue</h1>
                <p>Invoice {invoice_number}</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p>This is a friendly reminder that your invoice is <strong>{days_overdue} day(s) overdue</strong>.</p>

                <div class="danger-box">
                    <strong>Action Required</strong><br>
                    Invoice <strong>{invoice_number}</strong> for <strong>{currency_symbol}{amount:,.2f}</strong> was due on <strong>{due_date}</strong>.
                </div>

                <p>To avoid service interruption, please make your payment as soon as possible.</p>

                <div class="button-container">
                    <a href="{pay_url}" class="button button-danger">Pay Now →</a>
                </div>

                <div class="info-box">
                    <strong>Having trouble paying?</strong><br>
                    Contact our billing team at <a href="mailto:billing@ai360.com">billing@ai360.com</a> to discuss payment options.
                </div>

                <hr class="divider">

                <p style="color: #6b7280; font-size: 14px;">If you've already made this payment, please disregard this email. Payments can take up to 24 hours to process.</p>

                <p>Best regards,<br><strong>AI360 Solutions Billing Team</strong></p>
            </div>
            <div class="footer">
                <p>© {year} AI360 Solutions. All rights reserved.</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"Payment overdue: Invoice {invoice_number} for {currency_symbol}{amount:,.2f}")

    # ============================================================
    # ALERT EMAILS
    # ============================================================

    @classmethod
    def usage_limit_warning(cls, context: Dict[str, Any]) -> str:
        """Usage limit approaching warning"""
        user_name = context.get('user_name', 'there')
        resource_type = context.get('resource_type', 'messages')
        current_usage = context.get('current_usage', 0)
        limit = context.get('limit', 1000)
        percentage = context.get('percentage', 80)
        upgrade_url = context.get('upgrade_url', '#')
        year = context.get('year', datetime.now().year)

        content = f"""
        <div class="container">
            <div class="header" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                <div class="header-icon">📊</div>
                <h1>Usage Alert</h1>
                <p>You're approaching your limit</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p>You've used <strong>{percentage}%</strong> of your monthly {resource_type} limit.</p>

                <div class="warning-box">
                    <strong>Current Usage</strong><br>
                    <span style="font-size: 24px; font-weight: 700; color: #d97706;">{current_usage:,}</span> / {limit:,} {resource_type}
                </div>

                <div style="background: #f9fafb; border-radius: 12px; padding: 4px; margin: 24px 0;">
                    <div style="background: linear-gradient(90deg, #f59e0b 0%, #fbbf24 100%); height: 24px; border-radius: 10px; width: {min(percentage, 100)}%;"></div>
                </div>

                <p>To avoid service interruption, consider upgrading your plan or managing your usage.</p>

                <div class="button-container">
                    <a href="{upgrade_url}" class="button">Upgrade Plan →</a>
                </div>

                <hr class="divider">

                <p style="color: #6b7280; font-size: 14px;">You'll receive another notification when you reach 100% of your limit.</p>

                <p>Best regards,<br><strong>The AI360 Team</strong></p>
            </div>
            <div class="footer">
                <p>© {year} AI360 Solutions. All rights reserved.</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"Usage Alert: {percentage}% of your {resource_type} limit used")

    @classmethod
    def usage_limit_reached(cls, context: Dict[str, Any]) -> str:
        """Usage limit reached notification"""
        user_name = context.get('user_name', 'there')
        resource_type = context.get('resource_type', 'messages')
        limit = context.get('limit', 1000)
        reset_date = context.get('reset_date', 'next month')
        upgrade_url = context.get('upgrade_url', '#')
        year = context.get('year', datetime.now().year)

        content = f"""
        <div class="container">
            <div class="header" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                <div class="header-icon">🚫</div>
                <h1>Limit Reached</h1>
                <p>Your {resource_type} limit has been reached</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p>You've reached your monthly limit of <strong>{limit:,} {resource_type}</strong>.</p>

                <div class="danger-box">
                    <strong>Service Impact</strong><br>
                    New {resource_type} will be blocked until your limit resets on <strong>{reset_date}</strong> or you upgrade your plan.
                </div>

                <p><strong>What are your options?</strong></p>

                <ul class="feature-list">
                    <li>
                        <span class="feature-icon">⬆️</span>
                        <span><strong>Upgrade your plan</strong> - Get more {resource_type} instantly</span>
                    </li>
                    <li>
                        <span class="feature-icon">⏰</span>
                        <span><strong>Wait for reset</strong> - Your limit resets on {reset_date}</span>
                    </li>
                    <li>
                        <span class="feature-icon">💳</span>
                        <span><strong>Purchase add-on</strong> - Buy additional {resource_type} for this month</span>
                    </li>
                </ul>

                <div class="button-container">
                    <a href="{upgrade_url}" class="button button-danger">Upgrade Now →</a>
                </div>

                <hr class="divider">

                <p style="color: #6b7280; font-size: 14px;">Need help? Contact us at <a href="mailto:support@ai360.com">support@ai360.com</a></p>

                <p>Best regards,<br><strong>The AI360 Team</strong></p>
            </div>
            <div class="footer">
                <p>© {year} AI360 Solutions. All rights reserved.</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"Action Required: Your {resource_type} limit has been reached")

    @classmethod
    def subscription_expiring(cls, context: Dict[str, Any]) -> str:
        """Subscription expiring soon alert"""
        user_name = context.get('user_name', 'there')
        plan_name = context.get('plan_name', 'Standard')
        expiry_date = context.get('expiry_date', 'N/A')
        days_left = context.get('days_left', 7)
        renew_url = context.get('renew_url', '#')
        year = context.get('year', datetime.now().year)

        content = f"""
        <div class="container">
            <div class="header" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                <div class="header-icon">📅</div>
                <h1>Subscription Expiring</h1>
                <p>{days_left} days remaining</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p>Your <strong>{plan_name}</strong> subscription will expire on <strong>{expiry_date}</strong>.</p>

                <div class="warning-box">
                    <strong>⏰ {days_left} days left</strong><br>
                    Renew now to continue enjoying uninterrupted service.
                </div>

                <p><strong>What you'll lose if you don't renew:</strong></p>

                <ul class="feature-list">
                    <li>
                        <span class="feature-icon">❌</span>
                        <span>AI Chatbot functionality</span>
                    </li>
                    <li>
                        <span class="feature-icon">❌</span>
                        <span>WhatsApp integration</span>
                    </li>
                    <li>
                        <span class="feature-icon">❌</span>
                        <span>Analytics and reporting</span>
                    </li>
                    <li>
                        <span class="feature-icon">❌</span>
                        <span>Priority support</span>
                    </li>
                </ul>

                <div class="button-container">
                    <a href="{renew_url}" class="button">Renew Subscription →</a>
                </div>

                <div class="info-box">
                    <strong>💡 Pro Tip</strong><br>
                    Enable auto-renewal to never worry about expiration again!
                </div>

                <hr class="divider">

                <p style="color: #6b7280; font-size: 14px;">Questions? Contact us at <a href="mailto:support@ai360.com">support@ai360.com</a></p>

                <p>Best regards,<br><strong>The AI360 Team</strong></p>
            </div>
            <div class="footer">
                <p>© {year} AI360 Solutions. All rights reserved.</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"Your subscription expires in {days_left} days - Renew now")

    @classmethod
    def subscription_cancelled(cls, context: Dict[str, Any]) -> str:
        """Subscription cancelled confirmation"""
        user_name = context.get('user_name', 'there')
        plan_name = context.get('plan_name', 'Standard')
        end_date = context.get('end_date', 'N/A')
        feedback_url = context.get('feedback_url', '#')
        reactivate_url = context.get('reactivate_url', '#')
        year = context.get('year', datetime.now().year)

        content = f"""
        <div class="container">
            <div class="header" style="background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);">
                <div class="header-icon">👋</div>
                <h1>We're Sorry to See You Go</h1>
                <p>Your subscription has been cancelled</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p>Your <strong>{plan_name}</strong> subscription has been cancelled as requested.</p>

                <div class="info-box">
                    <strong>📅 Access Until</strong><br>
                    You'll continue to have access to your account until <strong>{end_date}</strong>.
                </div>

                <p>After this date:</p>
                <ul>
                    <li>Your chatbots will be deactivated</li>
                    <li>Data will be retained for 30 days</li>
                    <li>You can reactivate anytime</li>
                </ul>

                <p>We'd love to know how we can improve. Your feedback helps us serve you better.</p>

                <div class="button-container">
                    <a href="{feedback_url}" class="button" style="background: #6b7280;">Share Feedback →</a>
                </div>

                <hr class="divider">

                <p style="text-align: center;">
                    <strong>Changed your mind?</strong><br>
                    <a href="{reactivate_url}" style="color: #3b82f6; text-decoration: none; font-weight: 600;">Reactivate your subscription →</a>
                </p>

                <p>Best regards,<br><strong>The AI360 Team</strong></p>
            </div>
            <div class="footer">
                <p>© {year} AI360 Solutions. All rights reserved.</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"Your {plan_name} subscription has been cancelled")

    @classmethod
    def security_alert_login(cls, context: Dict[str, Any]) -> str:
        """New login security alert"""
        user_name = context.get('user_name', 'there')
        login_time = context.get('login_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        ip_address = context.get('ip_address', 'Unknown')
        location = context.get('location', 'Unknown')
        device = context.get('device', 'Unknown')
        browser = context.get('browser', 'Unknown')
        secure_account_url = context.get('secure_account_url', '#')
        year = context.get('year', datetime.now().year)

        content = f"""
        <div class="container">
            <div class="header" style="background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);">
                <div class="header-icon">🔐</div>
                <h1>New Login Detected</h1>
                <p>Security notification</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p>We noticed a new login to your AI360 account. If this was you, no action is needed.</p>

                <div style="background: #f9fafb; border-radius: 12px; padding: 24px; margin: 24px 0;">
                    <table style="width: 100%;">
                        <tr>
                            <td style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                <span style="color: #6b7280;">📅 Time</span>
                            </td>
                            <td style="padding: 8px 0; text-align: right; border-bottom: 1px solid #e5e7eb;">
                                <strong>{login_time}</strong>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                <span style="color: #6b7280;">🌍 Location</span>
                            </td>
                            <td style="padding: 8px 0; text-align: right; border-bottom: 1px solid #e5e7eb;">
                                <strong>{location}</strong>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                <span style="color: #6b7280;">💻 Device</span>
                            </td>
                            <td style="padding: 8px 0; text-align: right; border-bottom: 1px solid #e5e7eb;">
                                <strong>{device}</strong>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                <span style="color: #6b7280;">🌐 Browser</span>
                            </td>
                            <td style="padding: 8px 0; text-align: right; border-bottom: 1px solid #e5e7eb;">
                                <strong>{browser}</strong>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0;">
                                <span style="color: #6b7280;">📍 IP Address</span>
                            </td>
                            <td style="padding: 8px 0; text-align: right;">
                                <code style="background: #f3f4f6; padding: 2px 8px; border-radius: 4px;">{ip_address}</code>
                            </td>
                        </tr>
                    </table>
                </div>

                <div class="danger-box">
                    <strong>🚨 Wasn't you?</strong><br>
                    If you didn't login, someone may have access to your account. Click below to secure it immediately.
                </div>

                <div class="button-container">
                    <a href="{secure_account_url}" class="button button-danger">Secure My Account →</a>
                </div>

                <hr class="divider">

                <p style="color: #6b7280; font-size: 14px;">For security tips, visit our <a href="#">Security Center</a>.</p>

                <p>Best regards,<br><strong>AI360 Security Team</strong></p>
            </div>
            <div class="footer">
                <p>© {year} AI360 Solutions. All rights reserved.</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"New login to your AI360 account from {location}")

    @classmethod
    def api_key_created(cls, context: Dict[str, Any]) -> str:
        """API key created notification"""
        user_name = context.get('user_name', 'there')
        key_name = context.get('key_name', 'New API Key')
        created_by = context.get('created_by', 'You')
        created_at = context.get('created_at', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        permissions = context.get('permissions', ['chat'])
        manage_keys_url = context.get('manage_keys_url', '#')
        year = context.get('year', datetime.now().year)

        permissions_html = "".join([f"<span class='badge badge-info' style='margin: 2px;'>{p}</span>" for p in permissions])

        content = f"""
        <div class="container">
            <div class="header" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                <div class="header-icon">🔑</div>
                <h1>API Key Created</h1>
                <p>A new API key has been generated</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p>A new API key has been created for your account.</p>

                <div class="success-box">
                    <strong>Key Details</strong><br>
                    <table style="width: 100%; margin-top: 10px;">
                        <tr>
                            <td style="padding: 4px 0;"><span style="color: #6b7280;">Name:</span></td>
                            <td style="padding: 4px 0;"><strong>{key_name}</strong></td>
                        </tr>
                        <tr>
                            <td style="padding: 4px 0;"><span style="color: #6b7280;">Created by:</span></td>
                            <td style="padding: 4px 0;"><strong>{created_by}</strong></td>
                        </tr>
                        <tr>
                            <td style="padding: 4px 0;"><span style="color: #6b7280;">Created at:</span></td>
                            <td style="padding: 4px 0;"><strong>{created_at}</strong></td>
                        </tr>
                        <tr>
                            <td style="padding: 4px 0;"><span style="color: #6b7280;">Permissions:</span></td>
                            <td style="padding: 4px 0;">{permissions_html}</td>
                        </tr>
                    </table>
                </div>

                <div class="warning-box">
                    <strong>⚠️ Security Notice</strong><br>
                    If you didn't create this API key, please revoke it immediately and secure your account.
                </div>

                <div class="button-container">
                    <a href="{manage_keys_url}" class="button">Manage API Keys →</a>
                </div>

                <hr class="divider">

                <p style="color: #6b7280; font-size: 14px;">Keep your API keys secure and never share them publicly.</p>

                <p>Best regards,<br><strong>AI360 Security Team</strong></p>
            </div>
            <div class="footer">
                <p>© {year} AI360 Solutions. All rights reserved.</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"New API key '{key_name}' created for your account")

    @classmethod
    def weekly_report(cls, context: Dict[str, Any]) -> str:
        """Weekly analytics report"""
        user_name = context.get('user_name', 'there')
        week_range = context.get('week_range', 'This Week')
        total_conversations = context.get('total_conversations', 0)
        total_messages = context.get('total_messages', 0)
        avg_response_time = context.get('avg_response_time', '0s')
        satisfaction_rate = context.get('satisfaction_rate', 0)
        top_topics = context.get('top_topics', [])
        dashboard_url = context.get('dashboard_url', '#')
        year = context.get('year', datetime.now().year)

        topics_html = ""
        if top_topics:
            topics_html = "<ol style='margin: 10px 0; padding-left: 20px;'>"
            for topic in top_topics[:5]:
                topics_html += f"<li style='padding: 4px 0;'>{topic.get('name', '')} ({topic.get('count', 0)} conversations)</li>"
            topics_html += "</ol>"

        content = f"""
        <div class="container">
            <div class="header">
                <div class="header-icon">📈</div>
                <h1>Weekly Report</h1>
                <p>{week_range}</p>
            </div>
            <div class="content">
                <p>Hi <strong>{user_name}</strong>,</p>

                <p>Here's your weekly AI360 performance summary:</p>

                <div style="display: table; width: 100%; margin: 24px 0;">
                    <div style="display: table-row;">
                        <div style="display: table-cell; text-align: center; padding: 20px; background: #f0f9ff; border-radius: 8px 0 0 8px;">
                            <div style="font-size: 32px; font-weight: 700; color: #3b82f6;">{total_conversations:,}</div>
                            <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Conversations</div>
                        </div>
                        <div style="display: table-cell; text-align: center; padding: 20px; background: #ecfdf5;">
                            <div style="font-size: 32px; font-weight: 700; color: #10b981;">{total_messages:,}</div>
                            <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Messages</div>
                        </div>
                        <div style="display: table-cell; text-align: center; padding: 20px; background: #fef3c7;">
                            <div style="font-size: 32px; font-weight: 700; color: #f59e0b;">{avg_response_time}</div>
                            <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Avg Response</div>
                        </div>
                        <div style="display: table-cell; text-align: center; padding: 20px; background: #fce7f3; border-radius: 0 8px 8px 0;">
                            <div style="font-size: 32px; font-weight: 700; color: #ec4899;">{satisfaction_rate}%</div>
                            <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Satisfaction</div>
                        </div>
                    </div>
                </div>

                {"<div class='info-box'><strong>🔥 Top Conversation Topics</strong>" + topics_html + "</div>" if topics_html else ""}

                <div class="button-container">
                    <a href="{dashboard_url}" class="button">View Full Report →</a>
                </div>

                <hr class="divider">

                <p style="color: #6b7280; font-size: 14px;">You're receiving this because you're subscribed to weekly reports. <a href="#">Manage preferences</a></p>

                <p>Best regards,<br><strong>The AI360 Team</strong></p>
            </div>
            <div class="footer">
                <p>© {year} AI360 Solutions. All rights reserved.</p>
            </div>
        </div>
        """
        return cls._base_template(content, f"Your AI360 Weekly Report: {total_conversations} conversations, {satisfaction_rate}% satisfaction")
