/**
 * Email Templates Module
 *
 * Contains all email template generators for the application.
 */

import type { EmailTemplate } from './core';

// =============================================================================
// Types
// =============================================================================

export type Language = 'ar' | 'en';
export type OtpPurpose = 'login' | 'signup' | 'reset';

// =============================================================================
// Base Styles
// =============================================================================

const BASE_STYLES = `
  body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
    line-height: 1.6;
    color: #1f2937;
    background: #f3f4f6;
    margin: 0;
    padding: 20px;
  }
  .email-wrapper { background: #f3f4f6; padding: 40px 20px; }
  .container {
    max-width: 600px;
    margin: 0 auto;
    background: white;
    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: white;
    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: white;
    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;
  }
  .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;
  }
`;

const OTP_STYLES = `
  .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', monospace;
    margin: 0;
    padding: 10px;
  }
  .otp-expiry {
    font-size: 13px;
    color: #065f46;
    margin-top: 15px;
    font-weight: 500;
  }
  .security-notice {
    background: #fef3c7;
    border-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;
  }
`;

const CTA_STYLES = `
  .cta-button {
    display: inline-block;
    background: #10b981;
    color: white;
    padding: 12px 30px;
    text-decoration: none;
    border-radius: 6px;
    margin: 20px 0;
    font-weight: 600;
  }
`;

// =============================================================================
// OTP Template
// =============================================================================

export function createOTPEmail(
  otp: string,
  language: Language,
  name?: string,
  purpose: OtpPurpose = 'login'
): EmailTemplate {
  const isArabic = language === 'ar';

  const greeting = name
    ? isArabic
      ? `مرحباً ${name}،`
      : `Hello ${name},`
    : isArabic
      ? 'مرحباً،'
      : 'Hello,';

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

  const subject = isArabic
    ? `رمز تسجيل الدخول الآمن - Mawidi`
    : `Your Secure Login Code - Mawidi`;

  const html = `
    <!DOCTYPE html>
    <html ${isArabic ? 'dir="rtl" lang="ar"' : 'lang="en"'}>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>
        ${BASE_STYLES}
        ${OTP_STYLES}
        ${isArabic ? '.security-notice { border-right: 4px solid #f59e0b; border-left: none; }' : ''}
      </style>
    </head>
    <body>
      <div class="email-wrapper">
        <div class="container">
          <div class="header">
            <div class="logo">Mawidi</div>
            <div class="header-subtitle">${isArabic ? 'منصة إدارة المواعيد الذكية' : 'Smart Appointment Management'}</div>
          </div>
          <div class="content">
            <p class="greeting">${greeting}</p>
            <p class="message">${purposeMessage[purpose]}</p>
            <div class="otp-container">
              <div class="otp-label">${isArabic ? 'رمز التحقق الخاص بك' : 'Your Verification Code'}</div>
              <div class="otp-code">${otp}</div>
              <div class="otp-expiry">${isArabic ? '⏱ صالح لمدة 10 دقائق' : '⏱ Valid for 10 minutes'}</div>
            </div>
            <div class="security-notice">
              <p><strong>${isArabic ? '🔒 ملاحظة أمنية:' : '🔒 Security Notice:'}</strong> ${
                isArabic
                  ? 'لا تشارك هذا الرمز مع أي شخص. فريق Mawidi لن يطلب منك أبداً مشاركة رمز التحقق.'
                  : 'Never share this code with anyone. The Mawidi team will never ask you to share your verification code.'
              }</p>
            </div>
            <p class="message">${
              isArabic
                ? 'إذا لم تطلب هذا الرمز، يمكنك تجاهل هذه الرسالة بأمان. حسابك محمي ولم يتم الوصول إليه.'
                : "If you didn't request this code, you can safely ignore this message. Your account remains secure and has not been accessed."
            }</p>
          </div>
          <div class="footer">
            <p class="footer-text">${isArabic ? 'هل تحتاج إلى مساعدة؟' : 'Need help?'} <a href="mailto:support@mawidi.com" class="support-link">${isArabic ? 'اتصل بالدعم' : 'Contact Support'}</a></p>
            <p class="footer-text">© ${new Date().getFullYear()} Mawidi. ${isArabic ? 'جميع الحقوق محفوظة.' : 'All rights reserved.'}</p>
          </div>
        </div>
      </div>
    </body>
    </html>
  `;

  const text = isArabic
    ? `${greeting}\n\n${purposeMessage[purpose]}\n\nرمز التحقق الخاص بك: ${otp}\n\n⏱ هذا الرمز صالح لمدة 10 دقائق فقط.\n\n🔒 ملاحظة أمنية: لا تشارك هذا الرمز مع أي شخص.\n\nإذا لم تطلب هذا الرمز، يرجى تجاهل هذه الرسالة.\n\n© ${new Date().getFullYear()} Mawidi. جميع الحقوق محفوظة.`
    : `${greeting}\n\n${purposeMessage[purpose]}\n\nYour verification code: ${otp}\n\n⏱ This code is valid for 10 minutes only.\n\n🔒 Security Notice: Never share this code with anyone.\n\nIf you didn't request this code, please ignore this message.\n\n© ${new Date().getFullYear()} Mawidi. All rights reserved.`;

  return { subject, html, text };
}

// =============================================================================
// Welcome Template
// =============================================================================

export function createWelcomeEmail(name: string, language: Language): EmailTemplate {
  const isArabic = language === 'ar';
  const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:9000';

  const subject = isArabic ? 'مرحباً بك في Mawidi!' : 'Welcome to Mawidi!';

  const html = `
    <!DOCTYPE html>
    <html ${isArabic ? 'dir="rtl" lang="ar"' : 'lang="en"'}>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>
        ${BASE_STYLES}
        ${CTA_STYLES}
      </style>
    </head>
    <body>
      <div class="email-wrapper">
        <div class="container">
          <div class="header">
            <h1>🎉 ${isArabic ? 'مرحباً بك في Mawidi!' : 'Welcome to Mawidi!'}</h1>
          </div>
          <div class="content">
            <p class="greeting">${isArabic ? `عزيزي ${name}،` : `Dear ${name},`}</p>
            <p class="message">${
              isArabic
                ? 'شكراً لانضمامك إلى Mawidi! نحن متحمسون لمساعدتك في تحويل إدارة المواعيد الخاصة بك.'
                : "Thank you for joining Mawidi! We're excited to help you transform your appointment management."
            }</p>
            <p><strong>${isArabic ? 'الخطوات التالية:' : 'Next Steps:'}</strong></p>
            <ol>
              <li>${isArabic ? 'أكمل ملف تعريف شركتك' : 'Complete your company profile'}</li>
              <li>${isArabic ? 'اختر خطة الاشتراك المناسبة' : 'Choose your subscription plan'}</li>
              <li>${isArabic ? 'ابدأ في جدولة المواعيد' : 'Start scheduling appointments'}</li>
            </ol>
            <a href="${appUrl}/${language}/dashboard" class="cta-button">
              ${isArabic ? 'ابدأ الآن' : 'Get Started'}
            </a>
          </div>
          <div class="footer">
            <p class="footer-text">© ${new Date().getFullYear()} Mawidi. ${isArabic ? 'جميع الحقوق محفوظة.' : 'All rights reserved.'}</p>
          </div>
        </div>
      </div>
    </body>
    </html>
  `;

  const text = isArabic
    ? `مرحباً ${name}،\n\nشكراً لانضمامك إلى Mawidi!\n\nالخطوات التالية:\n1. أكمل ملف تعريف شركتك\n2. اختر خطة الاشتراك المناسبة\n3. ابدأ في جدولة المواعيد\n\n© ${new Date().getFullYear()} Mawidi. جميع الحقوق محفوظة.`
    : `Dear ${name},\n\nThank you for joining Mawidi!\n\nNext Steps:\n1. Complete your company profile\n2. Choose your subscription plan\n3. Start scheduling appointments\n\n© ${new Date().getFullYear()} Mawidi. All rights reserved.`;

  return { subject, html, text };
}

// =============================================================================
// Password Reset Template
// =============================================================================

export function createPasswordResetEmail(otp: string, language: Language): EmailTemplate {
  return createOTPEmail(otp, language, undefined, 'reset');
}

// =============================================================================
// Demo Confirmation Template
// =============================================================================

export function createDemoConfirmationEmail(
  name: string,
  date: string,
  time: string,
  duration: string,
  language: Language
): EmailTemplate {
  const isArabic = language === 'ar';
  const _appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:9000';

  const subject = isArabic
    ? 'تأكيد موعد العرض التجريبي - Mawidi'
    : 'Demo Appointment Confirmed - Mawidi';

  const html = `
    <!DOCTYPE html>
    <html ${isArabic ? 'dir="rtl" lang="ar"' : 'lang="en"'}>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>
        ${BASE_STYLES}
        ${CTA_STYLES}
        .demo-details {
          background: #f0fdf4;
          border: 1px solid #10b981;
          border-radius: 12px;
          padding: 24px;
          margin: 24px 0;
        }
        .demo-details p {
          margin: 8px 0;
          color: #065f46;
        }
      </style>
    </head>
    <body>
      <div class="email-wrapper">
        <div class="container">
          <div class="header">
            <div class="logo">Mawidi</div>
            <div class="header-subtitle">${isArabic ? 'تأكيد العرض التجريبي' : 'Demo Confirmation'}</div>
          </div>
          <div class="content">
            <p class="greeting">${isArabic ? `مرحباً ${name}،` : `Hello ${name},`}</p>
            <p class="message">${
              isArabic
                ? 'تم تأكيد موعد العرض التجريبي الخاص بك!'
                : 'Your demo appointment has been confirmed!'
            }</p>
            <div class="demo-details">
              <p><strong>${isArabic ? '📅 التاريخ:' : '📅 Date:'}</strong> ${date}</p>
              <p><strong>${isArabic ? '⏰ الوقت:' : '⏰ Time:'}</strong> ${time}</p>
              <p><strong>${isArabic ? '⏱ المدة:' : '⏱ Duration:'}</strong> ${duration}</p>
            </div>
            <p class="message">${
              isArabic
                ? 'سنرسل لك رابط الاجتماع قبل الموعد بـ 15 دقيقة.'
                : "We'll send you the meeting link 15 minutes before your appointment."
            }</p>
          </div>
          <div class="footer">
            <p class="footer-text">${isArabic ? 'هل لديك أسئلة؟' : 'Have questions?'} <a href="mailto:support@mawidi.com" class="support-link">${isArabic ? 'تواصل معنا' : 'Contact us'}</a></p>
            <p class="footer-text">© ${new Date().getFullYear()} Mawidi. ${isArabic ? 'جميع الحقوق محفوظة.' : 'All rights reserved.'}</p>
          </div>
        </div>
      </div>
    </body>
    </html>
  `;

  const text = isArabic
    ? `مرحباً ${name}،\n\nتم تأكيد موعد العرض التجريبي الخاص بك!\n\n📅 التاريخ: ${date}\n⏰ الوقت: ${time}\n⏱ المدة: ${duration}\n\nسنرسل لك رابط الاجتماع قبل الموعد بـ 15 دقيقة.\n\n© ${new Date().getFullYear()} Mawidi`
    : `Hello ${name},\n\nYour demo appointment has been confirmed!\n\n📅 Date: ${date}\n⏰ Time: ${time}\n⏱ Duration: ${duration}\n\nWe'll send you the meeting link 15 minutes before your appointment.\n\n© ${new Date().getFullYear()} Mawidi`;

  return { subject, html, text };
}

// =============================================================================
// Signup Welcome Template
// =============================================================================

export function createSignupWelcomeEmail(name: string, language: Language): EmailTemplate {
  return createWelcomeEmail(name, language);
}
