/**
 * Email Template Service - Professional Implementation
 *
 * Generates professional, brand-consistent email templates with:
 * - Personalization support
 * - Purpose-specific messaging
 * - Responsive design
 * - Bilingual support (Arabic/English)
 * - Accessibility features
 *
 * @module lib/services/email-template.service
 */

import type { Language, OTPPurpose, OTPEmailTemplate } from '@/lib/types/otp.types';

/**
 * Email template configuration
 */
const EMAIL_CONFIG = {
  brandName: 'Mawidi',
  brandTaglineEn: 'Smart Appointment Management',
  brandTaglineAr: 'منصة إدارة المواعيد الذكية',
  supportEmail: 'support@mawidi.com',
  companyYear: new Date().getFullYear(),
} as const;

/**
 * Purpose-specific email messages
 */
const EMAIL_MESSAGES = {
  login: {
    en: 'You requested to log in to your Mawidi account. Use the verification code below to complete your secure login:',
    ar: 'لقد طلبت تسجيل الدخول إلى حسابك في Mawidi. استخدم رمز التحقق التالي لإكمال عملية تسجيل الدخول بأمان:',
  },
  signup: {
    en: 'Thank you for choosing Mawidi! Use the verification code below to complete your registration:',
    ar: 'شكراً لاختيارك Mawidi! استخدم رمز التحقق التالي لإكمال عملية التسجيل:',
  },
  reset: {
    en: 'You requested to reset your password. Use the verification code below:',
    ar: 'لقد طلبت إعادة تعيين كلمة المرور الخاصة بك. استخدم رمز التحقق التالي:',
  },
} as const;

/**
 * Email Template Service Class
 *
 * @class EmailTemplateService
 */
class EmailTemplateService {
  /**
   * Create personalized OTP email template
   *
   * @param otpCode - 6-digit OTP code
   * @param language - Email language (ar/en)
   * @param userName - User's name for personalization (optional)
   * @param purpose - Purpose of the OTP
   * @returns Professional email template
   *
   * @example
   * ```typescript
   * const template = emailTemplateService.createOTPEmail(
   *   '123456',
   *   'en',
   *   'John Doe',
   *   'login'
   * );
   * ```
   */
  createOTPEmail(
    otpCode: string,
    language: Language,
    userName?: string,
    purpose: OTPPurpose = 'login'
  ): OTPEmailTemplate {
    const isArabic = language === 'ar';

    return {
      subject: this.getSubject(isArabic),
      html: this.getHTMLTemplate(otpCode, isArabic, userName, purpose),
      text: this.getTextTemplate(otpCode, isArabic, userName, purpose),
    };
  }

  /**
   * Get email subject line
   *
   * @private
   */
  private getSubject(isArabic: boolean): string {
    return isArabic
      ? `رمز تسجيل الدخول الآمن - ${EMAIL_CONFIG.brandName}`
      : `Your Secure Login Code - ${EMAIL_CONFIG.brandName}`;
  }

  /**
   * Get personalized greeting
   *
   * @private
   */
  private getGreeting(isArabic: boolean, userName?: string): string {
    if (!userName) {
      return isArabic ? 'مرحباً،' : 'Hello,';
    }

    return isArabic
      ? `مرحباً ${userName}،`
      : `Hello ${userName},`;
  }

  /**
   * Get purpose-specific message
   *
   * @private
   */
  private getMessage(purpose: OTPPurpose, isArabic: boolean): string {
    return isArabic
      ? EMAIL_MESSAGES[purpose].ar
      : EMAIL_MESSAGES[purpose].en;
  }

  /**
   * Generate HTML email template with professional design
   *
   * @private
   */
  private getHTMLTemplate(
    otpCode: string,
    isArabic: boolean,
    userName?: string,
    purpose: OTPPurpose = 'login'
  ): string {
    const greeting = this.getGreeting(isArabic, userName);
    const message = this.getMessage(purpose, isArabic);
    const direction = isArabic ? 'rtl' : 'ltr';
    const lang = isArabic ? 'ar' : 'en';

    return `
      <!DOCTYPE html>
      <html dir="${direction}" lang="${lang}">
      <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>${this.getSubject(isArabic)}</title>
        ${this.getStyles()}
      </head>
      <body>
        <div class="email-wrapper">
          <div class="container">
            ${this.getHeader(isArabic)}
            ${this.getContent(greeting, message, otpCode, isArabic)}
            ${this.getFooter(isArabic)}
          </div>
        </div>
      </body>
      </html>
    `;
  }

  /**
   * Get CSS styles for email template
   *
   * @private
   */
  private getStyles(): string {
    return `
      <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', Arial, sans-serif;
          line-height: 1.6;
          color: #1f2937;
          background: #f3f4f6;
          margin: 0;
          padding: 0;
        }
        .email-wrapper {
          background: #f3f4f6;
          padding: 40px 20px;
        }
        .container {
          max-width: 600px;
          margin: 0 auto;
          background: #ffffff;
          border-radius: 16px;
          overflow: hidden;
          box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .header {
          background: linear-gradient(135deg, #10b981 0%, #059669 100%);
          color: #ffffff;
          padding: 40px 30px;
          text-align: center;
        }
        .logo {
          font-size: 32px;
          font-weight: 800;
          margin-bottom: 8px;
          letter-spacing: -0.5px;
        }
        .header-subtitle {
          font-size: 16px;
          opacity: 0.95;
          font-weight: 500;
        }
        .content {
          background: #ffffff;
          padding: 40px 30px;
        }
        .greeting {
          font-size: 18px;
          font-weight: 600;
          color: #1f2937;
          margin-bottom: 20px;
        }
        .message {
          font-size: 15px;
          color: #4b5563;
          margin-bottom: 30px;
          line-height: 1.7;
        }
        .otp-container {
          background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
          border: 2px solid #10b981;
          border-radius: 12px;
          padding: 30px;
          margin: 30px 0;
          text-align: center;
        }
        .otp-label {
          font-size: 13px;
          color: #065f46;
          font-weight: 600;
          text-transform: uppercase;
          letter-spacing: 1px;
          margin-bottom: 15px;
        }
        .otp-code {
          font-size: 36px;
          font-weight: 800;
          letter-spacing: 12px;
          color: #059669;
          font-family: 'Courier New', Consolas, monospace;
          margin: 10px 0;
        }
        .otp-expiry {
          font-size: 13px;
          color: #065f46;
          margin-top: 15px;
          font-weight: 500;
        }
        .security-notice {
          background: #fef3c7;
          border-${isArabic ? 'right' : 'left'}: 4px solid #f59e0b;
          padding: 20px;
          border-radius: 8px;
          margin: 25px 0;
        }
        .security-notice p {
          margin: 0;
          font-size: 14px;
          color: #92400e;
          font-weight: 500;
        }
        .footer {
          background: #f9fafb;
          padding: 30px;
          text-align: center;
          border-top: 1px solid #e5e7eb;
        }
        .footer-text {
          color: #6b7280;
          font-size: 13px;
          margin: 5px 0;
        }
        .support-link {
          color: #10b981;
          text-decoration: none;
          font-weight: 600;
        }
        @media only screen and (max-width: 600px) {
          .email-wrapper { padding: 20px 10px; }
          .content { padding: 30px 20px; }
          .otp-code { font-size: 28px; letter-spacing: 8px; }
        }
      </style>
    `;
  }

  /**
   * Get email header section
   *
   * @private
   */
  private getHeader(isArabic: boolean): string {
    return `
      <div class="header">
        <div class="logo">${EMAIL_CONFIG.brandName}</div>
        <div class="header-subtitle">
          ${isArabic ? EMAIL_CONFIG.brandTaglineAr : EMAIL_CONFIG.brandTaglineEn}
        </div>
      </div>
    `;
  }

  /**
   * Get email content section
   *
   * @private
   */
  private getContent(
    greeting: string,
    message: string,
    otpCode: string,
    isArabic: boolean
  ): string {
    const otpLabel = isArabic ? 'رمز التحقق الخاص بك' : 'Your Verification Code';
    const expiryText = isArabic ? '⏱ صالح لمدة 10 دقائق' : '⏱ Valid for 10 minutes';
    const securityTitle = isArabic ? '🔒 ملاحظة أمنية:' : '🔒 Security Notice:';
    const securityMessage = isArabic
      ? 'لا تشارك هذا الرمز مع أي شخص. فريق Mawidi لن يطلب منك أبداً مشاركة رمز التحقق.'
      : 'Never share this code with anyone. The Mawidi team will never ask you to share your verification code.';
    const footerMessage = isArabic
      ? 'إذا لم تطلب هذا الرمز، يمكنك تجاهل هذه الرسالة بأمان. حسابك محمي ولم يتم الوصول إليه.'
      : 'If you didn\'t request this code, you can safely ignore this message. Your account remains secure and has not been accessed.';

    return `
      <div class="content">
        <p class="greeting">${greeting}</p>
        <p class="message">${message}</p>

        <div class="otp-container">
          <div class="otp-label">${otpLabel}</div>
          <div class="otp-code">${otpCode}</div>
          <div class="otp-expiry">${expiryText}</div>
        </div>

        <div class="security-notice">
          <p><strong>${securityTitle}</strong> ${securityMessage}</p>
        </div>

        <p class="message">${footerMessage}</p>
      </div>
    `;
  }

  /**
   * Get email footer section
   *
   * @private
   */
  private getFooter(isArabic: boolean): string {
    const helpText = isArabic ? 'هل تحتاج إلى مساعدة؟' : 'Need help?';
    const contactText = isArabic ? 'اتصل بالدعم' : 'Contact Support';
    const copyrightText = isArabic
      ? `© ${EMAIL_CONFIG.companyYear} ${EMAIL_CONFIG.brandName}. جميع الحقوق محفوظة.`
      : `© ${EMAIL_CONFIG.companyYear} ${EMAIL_CONFIG.brandName}. All rights reserved.`;

    return `
      <div class="footer">
        <p class="footer-text">
          ${helpText}
          <a href="mailto:${EMAIL_CONFIG.supportEmail}" class="support-link">${contactText}</a>
        </p>
        <p class="footer-text">${copyrightText}</p>
      </div>
    `;
  }

  /**
   * Generate plain text version of email
   *
   * @private
   */
  private getTextTemplate(
    otpCode: string,
    isArabic: boolean,
    userName?: string,
    purpose: OTPPurpose = 'login'
  ): string {
    const greeting = this.getGreeting(isArabic, userName);
    const message = this.getMessage(purpose, isArabic);

    const otpLabel = isArabic ? 'رمز التحقق الخاص بك:' : 'Your verification code:';
    const expiryText = isArabic
      ? '⏱ هذا الرمز صالح لمدة 10 دقائق فقط.'
      : '⏱ This code is valid for 10 minutes only.';
    const securityNote = isArabic
      ? '🔒 ملاحظة أمنية: لا تشارك هذا الرمز مع أي شخص.'
      : '🔒 Security Notice: Never share this code with anyone.';
    const ignoreMessage = isArabic
      ? 'إذا لم تطلب هذا الرمز، يرجى تجاهل هذه الرسالة.'
      : 'If you didn\'t request this code, please ignore this message.';
    const copyright = isArabic
      ? `© ${EMAIL_CONFIG.companyYear} ${EMAIL_CONFIG.brandName}. جميع الحقوق محفوظة.`
      : `© ${EMAIL_CONFIG.companyYear} ${EMAIL_CONFIG.brandName}. All rights reserved.`;

    return `
${greeting}

${message}

${otpLabel} ${otpCode}

${expiryText}

${securityNote}

${ignoreMessage}

${copyright}
    `.trim();
  }
}

/**
 * Singleton instance of Email Template Service
 *
 * @example
 * ```typescript
 * import { emailTemplateService } from '@/lib/services/email-template.service';
 *
 * const template = emailTemplateService.createOTPEmail(
 *   '123456',
 *   'en',
 *   'John Doe',
 *   'login'
 * );
 * ```
 */
export const emailTemplateService = new EmailTemplateService();
