package com.saas.shared.email;

import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Email Template Builder Service
 * Creates HTML email templates for various use cases
 */
@Service
public class EmailTemplateService {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");

    /**
     * Template for new doctor account creation with credentials
     */
    public String buildDoctorWelcomeEmail(String firstName, String lastName,
            String email, String password,
            String tenantName, String loginUrl) {
        return """
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <style>
                        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                        .header { background: linear-gradient(135deg, #667eea 0%%, #764ba2 100%%);
                                  color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
                        .content { background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px; }
                        .credentials { background: white; padding: 20px; border-left: 4px solid #667eea;
                                       margin: 20px 0; border-radius: 5px; }
                        .button { display: inline-block; background: #667eea; color: white;
                                  padding: 12px 30px; text-decoration: none; border-radius: 5px;
                                  margin-top: 20px; }
                        .warning { background: #fff3cd; border-left: 4px solid #ffc107;
                                   padding: 15px; margin: 20px 0; border-radius: 5px; }
                        .footer { text-align: center; color: #666; font-size: 12px; margin-top: 30px; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <div class="header">
                            <h1>🎉 Bienvenue sur la plateforme !</h1>
                        </div>
                        <div class="content">
                            <h2>Bonjour Dr. %s %s,</h2>
                            <p>Votre compte médecin a été créé avec succès sur la plateforme <strong>%s</strong>.</p>

                            <div class="credentials">
                                <h3>🔐 Vos identifiants de connexion :</h3>
                                <p><strong>Email :</strong> %s</p>
                                <p><strong>Mot de passe :</strong> <code style="background: #f0f0f0; padding: 5px 10px;
                                   border-radius: 3px; font-size: 16px;">%s</code></p>
                            </div>

                            <div class="warning">
                                <strong>⚠️ Important :</strong> Pour des raisons de sécurité, veuillez changer votre mot de passe
                                lors de votre première connexion.
                            </div>

                            <a href="%s" class="button">Se connecter maintenant</a>

                            <p style="margin-top: 30px;">Si vous avez des questions, n'hésitez pas à contacter l'administrateur.</p>

                            <p>Cordialement,<br>
                            <strong>L'équipe %s</strong></p>
                        </div>
                        <div class="footer">
                            <p>Cet email a été généré automatiquement. Merci de ne pas y répondre.</p>
                        </div>
                    </div>
                </body>
                </html>
                """
                .formatted(firstName, lastName, tenantName, email, password, loginUrl, tenantName);
    }

    /**
     * Template for monthly invoice to tenant admins
     */
    public String buildMonthlyInvoiceEmail(String tenantName, String adminName,
            String billingPeriod, BigDecimal baseAmount,
            int includedMinutes, int usedMinutes, int overageMinutes,
            BigDecimal overageAmount, BigDecimal totalAmount,
            String invoiceUrl) {
        return """
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <style>
                        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                        .container { max-width: 700px; margin: 0 auto; padding: 20px; }
                        .header { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
                                  color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
                        .content { background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px; }
                        .invoice-box { background: white; padding: 25px; border-radius: 8px; margin: 20px 0; }
                        .invoice-table { width: 100%%; border-collapse: collapse; margin: 20px 0; }
                        .invoice-table th { background: #f0f0f0; padding: 12px; text-align: left; border-bottom: 2px solid #ddd; }
                        .invoice-table td { padding: 12px; border-bottom: 1px solid #eee; }
                        .total-row { font-weight: bold; background: #f8f9fa; font-size: 18px; }
                        .button { display: inline-block; background: #11998e; color: white;
                                  padding: 12px 30px; text-decoration: none; border-radius: 5px; margin-top: 20px; }
                        .alert { background: #f8d7da; border-left: 4px solid #dc3545; padding: 15px;
                                 margin: 20px 0; border-radius: 5px; color: #721c24; }
                        .footer { text-align: center; color: #666; font-size: 12px; margin-top: 30px; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <div class="header">
                            <h1>📊 Facture Mensuelle</h1>
                            <p style="font-size: 18px; margin: 10px 0;">Période : %s</p>
                        </div>
                        <div class="content">
                            <h2>Bonjour %s,</h2>
                            <p>Voici votre facture mensuelle pour <strong>%s</strong>.</p>

                            <div class="invoice-box">
                                <h3>Détails de facturation</h3>
                                <table class="invoice-table">
                                    <tr>
                                        <th>Description</th>
                                        <th style="text-align: right;">Quantité</th>
                                        <th style="text-align: right;">Montant</th>
                                    </tr>
                                    <tr>
                                        <td>Abonnement mensuel</td>
                                        <td style="text-align: right;">1</td>
                                        <td style="text-align: right;">%s €</td>
                                    </tr>
                                    <tr>
                                        <td>Minutes incluses</td>
                                        <td style="text-align: right;">%d min</td>
                                        <td style="text-align: right;">Inclus</td>
                                    </tr>
                                    <tr>
                                        <td>Minutes utilisées</td>
                                        <td style="text-align: right;">%d min</td>
                                        <td style="text-align: right;">-</td>
                                    </tr>
                                    %s
                                    <tr class="total-row">
                                        <td colspan="2">TOTAL</td>
                                        <td style="text-align: right;">%s €</td>
                                    </tr>
                                </table>
                            </div>

                            %s

                            <a href="%s" class="button">Télécharger la facture PDF</a>

                            <p style="margin-top: 30px;">Merci de votre confiance !</p>

                            <p>Cordialement,<br>
                            <strong>L'équipe SaaS VoIP Platform</strong></p>
                        </div>
                        <div class="footer">
                            <p>© 2024 SaaS VoIP Platform. Tous droits réservés.</p>
                            <p>Cet email a été généré automatiquement.</p>
                        </div>
                    </div>
                </body>
                </html>
                """
                .formatted(
                        billingPeriod, adminName, tenantName,
                        baseAmount, includedMinutes, usedMinutes,
                        overageMinutes > 0 ? String.format(
                                "<tr><td>Dépassement (%d min)</td><td style=\"text-align: right;\">%d min</td><td style=\"text-align: right;\">%s €</td></tr>",
                                overageMinutes, overageMinutes, overageAmount) : "",
                        totalAmount,
                        overageMinutes > 0
                                ? "<div class=\"alert\"><strong>⚠️ Dépassement détecté :</strong> Vous avez dépassé votre quota de minutes incluses. Des frais supplémentaires ont été appliqués.</div>"
                                : "",
                        invoiceUrl != null ? invoiceUrl : "#");
    }

    /**
     * Template for subscription payment notification to SYSTEM_ADMIN
     */
    public String buildSubscriptionPaymentNotification(String tenantName, String tenantId,
            String planName, BigDecimal amount,
            String paymentStatus, LocalDateTime paymentDate,
            String stripePaymentIntentId) {
        return """
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <style>
                        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                        .container { max-width: 650px; margin: 0 auto; padding: 20px; }
                        .header { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
                                  color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
                        .content { background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px; }
                        .payment-box { background: white; padding: 25px; border-radius: 8px; margin: 20px 0;
                                       box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
                        .info-row { display: flex; justify-content: space-between; padding: 12px 0;
                                    border-bottom: 1px solid #eee; }
                        .info-label { font-weight: bold; color: #666; }
                        .info-value { color: #333; }
                        .status-success { display: inline-block; background: #d4edda; color: #155724;
                                          padding: 5px 15px; border-radius: 20px; font-weight: bold; }
                        .status-failed { display: inline-block; background: #f8d7da; color: #721c24;
                                         padding: 5px 15px; border-radius: 20px; font-weight: bold; }
                        .footer { text-align: center; color: #666; font-size: 12px; margin-top: 30px; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <div class="header">
                            <h1>💳 Nouveau Paiement Reçu</h1>
                        </div>
                        <div class="content">
                            <h2>Notification de paiement</h2>
                            <p>Un nouveau paiement d'abonnement a été effectué sur la plateforme.</p>

                            <div class="payment-box">
                                <h3>📋 Détails du paiement</h3>

                                <div class="info-row">
                                    <span class="info-label">Tenant :</span>
                                    <span class="info-value">%s (ID: %s)</span>
                                </div>

                                <div class="info-row">
                                    <span class="info-label">Plan souscrit :</span>
                                    <span class="info-value">%s</span>
                                </div>

                                <div class="info-row">
                                    <span class="info-label">Montant :</span>
                                    <span class="info-value" style="font-size: 20px; color: #28a745; font-weight: bold;">%s €</span>
                                </div>

                                <div class="info-row">
                                    <span class="info-label">Date :</span>
                                    <span class="info-value">%s</span>
                                </div>

                                <div class="info-row">
                                    <span class="info-label">Statut :</span>
                                    <span class="%s">%s</span>
                                </div>

                                <div class="info-row">
                                    <span class="info-label">Payment Intent ID :</span>
                                    <span class="info-value"><code>%s</code></span>
                                </div>
                            </div>

                            <p style="margin-top: 20px; color: #666; font-size: 14px;">
                                <strong>Note :</strong> Cette notification est envoyée automatiquement à tous les
                                administrateurs système pour le suivi des revenus.
                            </p>
                        </div>
                        <div class="footer">
                            <p>© 2024 SaaS VoIP Platform - Admin Dashboard</p>
                            <p>Cet email a été généré automatiquement.</p>
                        </div>
                    </div>
                </body>
                </html>
                """
                .formatted(
                        tenantName, tenantId, planName, amount,
                        paymentDate.format(DATE_FORMATTER),
                        paymentStatus.equalsIgnoreCase("succeeded") ? "status-success" : "status-failed",
                        paymentStatus.toUpperCase(),
                        stripePaymentIntentId);
    }

    /**
     * Simple test email template
     */
    public String buildTestEmail(String recipientName) {
        return """
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <style>
                        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                                  color: white; padding: 30px; text-align: center; border-radius: 10px; }
                        .content { padding: 30px; }
                        .success-icon { font-size: 60px; text-align: center; margin: 20px 0; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <div class="header">
                            <h1>✉️ Email de Test</h1>
                        </div>
                        <div class="content">
                            <div class="success-icon">✅</div>
                            <h2>Bonjour %s,</h2>
                            <p>Ceci est un email de test envoyé depuis la plateforme SaaS VoIP.</p>
                            <p>Si vous recevez cet email, cela signifie que l'intégration Brevo fonctionne correctement !</p>
                            <p style="margin-top: 30px; color: #666; font-size: 14px;">
                                Date d'envoi : %s
                            </p>
                        </div>
                    </div>
                </body>
                </html>
                """
                .formatted(recipientName, LocalDateTime.now().format(DATE_FORMATTER));
    }

    /**
     * Template for new tenant welcome email
     */
    public String buildTenantWelcomeEmail(String firstName, String tenantName, String email, String loginUrl) {
        return """
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <style>
                        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                        .header { background: linear-gradient(135deg, #11998e 0%%, #38ef7d 100%%);
                                  color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
                        .content { background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px; }
                        .feature-box { background: white; padding: 20px; border-radius: 8px; margin: 20px 0;
                                       box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
                        .button { display: inline-block; background: #11998e; color: white;
                                  padding: 12px 30px; text-decoration: none; border-radius: 5px; margin-top: 20px; }
                        .footer { text-align: center; color: #666; font-size: 12px; margin-top: 30px; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <div class="header">
                            <h1>🚀 Bienvenue chez SaaS VoIP !</h1>
                        </div>
                        <div class="content">
                            <h2>Bonjour %s,</h2>
                            <p>Félicitations pour la création de votre espace <strong>%s</strong> ! Nous sommes ravis de vous compter parmi nous.</p>

                            <p>Votre plateforme de gestion médicale et de téléphonie IA est prête. Vous pouvez dès maintenant :</p>

                            <div class="feature-box">
                                <ul style="padding-left: 20px; margin: 0;">
                                    <li style="margin-bottom: 10px;">📞 Configurer vos numéros de téléphone</li>
                                    <li style="margin-bottom: 10px;">🩺 Créer des comptes pour vos médecins</li>
                                    <li style="margin-bottom: 10px;">🤖 Personnaliser vos assistants IA (Vapi/Retell)</li>
                                    <li>📅 Gérer vos rendez-vous et votre agenda</li>
                                </ul>
                            </div>

                            <p>Pour commencer, connectez-vous à votre tableau de bord administrateur :</p>

                            <div style="text-align: center;">
                                <a href="%s" class="button">Accéder à mon Espace</a>
                            </div>

                            <p style="margin-top: 30px;">
                                <strong>Besoin d'aide ?</strong> Notre équipe support est à votre disposition pour vous accompagner dans le paramétrage.
                            </p>

                            <p>Cordialement,<br>
                            <strong>L'équipe SaaS VoIP Platform</strong></p>
                        </div>
                        <div class="footer">
                            <p>© 2024 SaaS VoIP Platform. Tous droits réservés.</p>
                            <p>Cet email a été envoyé à %s pour confirmer votre inscription.</p>
                        </div>
                    </div>
                </body>
                </html>
                """
                .formatted(firstName, tenantName, loginUrl, email);
    }
}
