import nodemailer from "nodemailer";

let _transporter: ReturnType<typeof nodemailer.createTransport> | null = null;

function getTransporter() {
  if (!_transporter) {
    _transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: process.env.SMTP_USER || process.env.EMAIL_USER,
        pass: process.env.SMTP_PASS || process.env.EMAIL_PASS,
      },
    });
  }
  return _transporter;
}

interface EmailOptions {
  to: string;
  subject: string;
  html: string;
}

export async function sendEmail({ to, subject, html }: EmailOptions) {
  try {
    const info = await getTransporter().sendMail({
      from: `AIUAG <${process.env.SMTP_USER || process.env.EMAIL_USER}>`,
      to,
      subject,
      html,
    });
    return { success: true, messageId: info.messageId };
  } catch (error) {
    console.error("Email send error:", error);
    return { success: false, error: "Failed to send email" };
  }
}

const BASE_URL = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:9000";
const CURRENT_YEAR = new Date().getFullYear();

function getBaseStyles(): string {
  return `
    @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap');
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: 'Tajawal', 'Segoe UI', Tahoma, sans-serif; background: #f0f2f5; margin: 0; padding: 0; direction: rtl; }
    .wrapper { width: 100%; background: #f0f2f5; padding: 40px 20px; }
    .container { max-width: 580px; margin: 0 auto; background: #ffffff; border-radius: 20px; overflow: hidden; box-shadow: 0 8px 40px rgba(0,0,0,0.08); }
    .header { background: linear-gradient(135deg, #1A3A6B 0%, #2B5EA7 60%, #1A3A6B 100%); padding: 48px 32px 36px; text-align: center; position: relative; overflow: hidden; }
    .header::before { content: ''; position: absolute; top: -80px; right: -80px; width: 200px; height: 200px; border-radius: 50%; background: rgba(212,168,67,0.15); }
    .header::after { content: ''; position: absolute; bottom: -100px; left: -60px; width: 240px; height: 240px; border-radius: 50%; background: rgba(255,255,255,0.05); }
    .logo-wrap { position: relative; z-index: 2; margin-bottom: 20px; }
    .header h1 { color: #ffffff; font-size: 26px; font-weight: 800; margin: 0; position: relative; z-index: 2; letter-spacing: 0.5px; }
    .header .subtitle { color: rgba(255,255,255,0.75); font-size: 14px; margin-top: 8px; position: relative; z-index: 2; }
    .body { padding: 40px 36px; text-align: center; }
    .body h2 { color: #1A3A6B; font-size: 22px; font-weight: 700; margin-bottom: 12px; }
    .body p { color: #5a6577; font-size: 15px; line-height: 1.9; margin-bottom: 16px; }
    .icon-box { width: 80px; height: 80px; margin: 0 auto 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; }
    .icon-box.green { background: #ecfdf5; }
    .icon-box.blue { background: #eff6ff; }
    .icon-box.amber { background: #fffbeb; }
    .icon-box.red { background: #fef2f2; }
    .btn-wrap { margin: 28px 0; }
    .btn { display: inline-block; background: linear-gradient(135deg, #1A3A6B, #2B5EA7); color: #ffffff !important; padding: 14px 44px; border-radius: 12px; text-decoration: none; font-weight: 700; font-size: 16px; box-shadow: 0 4px 20px rgba(26,58,107,0.35); letter-spacing: 0.3px; }
    .btn.gold { background: linear-gradient(135deg, #D4A843, #E8C76A); box-shadow: 0 4px 20px rgba(212,168,67,0.35); color: #1A3A6B !important; }
    .btn.red { background: linear-gradient(135deg, #dc2626, #ef4444); box-shadow: 0 4px 20px rgba(220,38,38,0.3); }
    .code-row { display: flex; justify-content: center; gap: 10px; margin: 28px 0; }
    .code-cell { width: 52px; height: 60px; background: linear-gradient(135deg, #1A3A6B, #2B5EA7); color: #ffffff; font-size: 26px; font-weight: 800; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-family: 'Courier New', monospace; box-shadow: 0 4px 14px rgba(26,58,107,0.3); }
    .divider { height: 1px; background: linear-gradient(to right, transparent, #e2e8f0, transparent); margin: 24px 0; }
    .alert { border-radius: 14px; padding: 16px 20px; margin: 20px 0; font-size: 14px; text-align: right; }
    .alert.amber { background: #fffbeb; border: 1px solid #fbbf24; color: #92400e; }
    .alert.red { background: #fef2f2; border: 1px solid #fca5a5; color: #991b1b; }
    .alert.green { background: #ecfdf5; border: 1px solid #6ee7b7; color: #065f46; }
    .info-row { display: flex; align-items: center; gap: 12px; padding: 14px 16px; background: #f8fafc; border-radius: 12px; margin: 8px 0; }
    .info-row .info-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
    .info-row .info-text { text-align: right; flex: 1; }
    .info-row .info-label { font-size: 12px; color: #94a3b8; margin-bottom: 2px; }
    .info-row .info-value { font-size: 15px; color: #1e293b; font-weight: 600; }
    .footer { background: #1A3A6B; padding: 32px; text-align: center; }
    .footer .brand { color: #ffffff; font-size: 16px; font-weight: 700; margin-bottom: 6px; }
    .footer .tagline { color: rgba(255,255,255,0.6); font-size: 13px; margin-bottom: 20px; }
    .footer .socials { margin-bottom: 20px; }
    .footer .socials a { display: inline-block; margin: 0 6px; width: 36px; height: 36px; border-radius: 50%; background: rgba(255,255,255,0.1); line-height: 36px; text-align: center; }
    .footer .copy { margin-top: 20px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.1); color: rgba(255,255,255,0.5); font-size: 12px; }
  `;
}

function getFooter(): string {
  return `
    <div class="footer">
      <div class="brand">رابطة خريجي جامعة أفريقيا العالمية</div>
      <div class="tagline">تعزيز الروابط المهنية والاجتماعية بين الخريجين</div>
      <div class="socials">
        <a href="#"><svg width="16" height="16" viewBox="0 0 24 24" fill="white"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg></a>
        <a href="#"><svg width="16" height="16" viewBox="0 0 24 24" fill="white"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg></a>
        <a href="#"><svg width="16" height="16" viewBox="0 0 24 24" fill="white"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/></svg></a>
      </div>
      <div class="copy">&copy; ${CURRENT_YEAR} جميع الحقوق محفوظة</div>
    </div>
  `;
}

export function getWelcomeEmailHtml(name: string, email: string): string {
  return `
    <!DOCTYPE html>
    <html dir="rtl" lang="ar">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>${getBaseStyles()}</style>
    </head>
    <body>
      <div class="wrapper">
        <div class="container">
          <!-- Header -->
          <div class="header">
            <div class="logo-wrap">
              <svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="32" cy="32" r="30" stroke="rgba(255,255,255,0.2)" stroke-width="2" fill="rgba(255,255,255,0.1)"/>
                <circle cx="32" cy="32" r="20" fill="#D4A843"/>
                <path d="M32 18L40 23V41L32 46L24 41V23L32 18Z" fill="#1A3A6B"/>
                <path d="M32 24L36 26.5V37.5L32 40L28 37.5V26.5L32 24Z" fill="#D4A843"/>
              </svg>
            </div>
            <h1>مرحباً بك في عائلتنا</h1>
            <div class="subtitle">رابطة خريجي جامعة أفريقيا العالمية</div>
          </div>

          <!-- Body -->
          <div class="body">
            <div class="icon-box green">
              <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
                <circle cx="20" cy="20" r="18" fill="#D4A843"/>
                <path d="M13 20L18 25L27 15" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>

            <h2>أهلاً وسهلاً ${name}</h2>
            <p>يسعدنا انضمامك إلى عائلة رابطة خريجي جامعة أفريقيا العالمية. أصبحت الآن جزءاً من شبكة مهنية متميزة تضم آلاف الخريجين حول العالم.</p>

            <div class="divider"></div>

            <div class="info-row">
              <div class="info-icon" style="background:#eff6ff;">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="7" r="3" fill="#1A3A6B"/><path d="M4 18c0-3.314 2.686-6 6-6s6 2.686 6 6" stroke="#1A3A6B" stroke-width="1.5" fill="none"/></svg>
              </div>
              <div class="info-text">
                <div class="info-label">البريد الإلكتروني</div>
                <div class="info-value" dir="ltr">${email}</div>
              </div>
            </div>

            <div class="info-row">
              <div class="info-icon" style="background:#ecfdf5;">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><rect x="2" y="4" width="16" height="12" rx="2" stroke="#059669" stroke-width="1.5" fill="none"/><path d="M2 8h16" stroke="#059669" stroke-width="1.5"/><rect x="4" y="12" width="6" height="2" rx="1" fill="#D4A843"/></svg>
              </div>
              <div class="info-text">
                <div class="info-label">المزايا المتاحة</div>
                <div class="info-value">ملف شخصي • بطاقة عضوية • مزايا حصرية</div>
              </div>
            </div>

            <div class="btn-wrap">
              <a href="${BASE_URL}/auth/login" class="btn">تسجيل الدخول الآن</a>
            </div>

            <div class="alert amber">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="#92400e" style="vertical-align:middle;margin-left:6px;"><path d="M8 1L1 14h14L8 1zM8 5v4M8 11v.5" stroke="#92400e" stroke-width="1.5" fill="none" stroke-linecap="round"/></svg>
             يرجى التحقق من بريدك الإلكتروني قبل تسجيل الدخول
            </div>
          </div>

          ${getFooter()}
        </div>
      </div>
    </body>
    </html>
  `;
}

export function getVerificationEmailHtml(name: string, token: string): string {
  const verifyUrl = `${BASE_URL}/api/auth/verify-email?token=${token}`;

  return `
    <!DOCTYPE html>
    <html dir="rtl" lang="ar">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>${getBaseStyles()}</style>
    </head>
    <body>
      <div class="wrapper">
        <div class="container">
          <!-- Header -->
          <div class="header">
            <div class="logo-wrap">
              <svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="32" cy="32" r="30" stroke="rgba(255,255,255,0.2)" stroke-width="2" fill="rgba(255,255,255,0.1)"/>
                <circle cx="32" cy="32" r="20" fill="#D4A843"/>
                <path d="M32 18L40 23V41L32 46L24 41V23L32 18Z" fill="#1A3A6B"/>
                <path d="M32 24L36 26.5V37.5L32 40L28 37.5V26.5L32 24Z" fill="#D4A843"/>
              </svg>
            </div>
            <h1>تأكيد البريد الإلكتروني</h1>
            <div class="subtitle">رابطة خريجي جامعة أفريقيا العالمية</div>
          </div>

          <!-- Body -->
          <div class="body">
            <div class="icon-box blue">
              <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
                <circle cx="20" cy="20" r="18" fill="#1A3A6B"/>
                <circle cx="20" cy="20" r="12" fill="white"/>
                <path d="M15 20L18 23L25 16" stroke="#1A3A6B" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>

            <h2>مرحباً ${name}</h2>
            <p>شكراً لك للانضمام إلى رابطة خريجي جامعة أفريقيا العالمية. لتأكيد حسابك، يرجى استخدام رمز التأكيد التالي:</p>

            <div class="code-row">
              ${token.split("").map((digit) => `<div class="code-cell">${digit}</div>`).join("")}
            </div>

            <p style="font-size:14px; color:#64748b; margin-bottom:24px;">أو اضغط على الزر أدناه للتأكيد السريع:</p>

            <div class="btn-wrap">
              <a href="${verifyUrl}" class="btn">تأكيد البريد الإلكتروني</a>
            </div>

            <div class="divider"></div>

            <div class="alert amber">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="#92400e" style="vertical-align:middle;margin-left:6px;"><path d="M8 1L1 14h14L8 1zM8 5v4M8 11v.5" stroke="#92400e" stroke-width="1.5" fill="none" stroke-linecap="round"/></svg>
              هذا الرمز صالح لمدة <strong>24 ساعة</strong> فقط
            </div>

            <p style="font-size:13px; color:#94a3b8;">إذا لم تطلب إنشاء هذا الحساب، يرجى تجاهل هذه الرسالة.</p>
          </div>

          ${getFooter()}
        </div>
      </div>
    </body>
    </html>
  `;
}

export function getPasswordResetEmailHtml(name: string, token: string): string {
  const resetUrl = `${BASE_URL}/auth/reset-password?token=${token}`;

  return `
    <!DOCTYPE html>
    <html dir="rtl" lang="ar">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>${getBaseStyles()}</style>
    </head>
    <body>
      <div class="wrapper">
        <div class="container">
          <!-- Header -->
          <div class="header">
            <div class="logo-wrap">
              <svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="32" cy="32" r="30" stroke="rgba(255,255,255,0.2)" stroke-width="2" fill="rgba(255,255,255,0.1)"/>
                <circle cx="32" cy="32" r="20" fill="#D4A843"/>
                <path d="M32 18L40 23V41L32 46L24 41V23L32 18Z" fill="#1A3A6B"/>
                <path d="M32 24L36 26.5V37.5L32 40L28 37.5V26.5L32 24Z" fill="#D4A843"/>
              </svg>
            </div>
            <h1>إعادة تعيين كلمة المرور</h1>
            <div class="subtitle">رابطة خريجي جامعة أفريقيا العالمية</div>
          </div>

          <!-- Body -->
          <div class="body">
            <div class="icon-box amber">
              <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
                <circle cx="20" cy="20" r="18" fill="#D4A843"/>
                <rect x="13" y="18" width="14" height="12" rx="2" fill="white"/>
                <path d="M16 18v-3a4 4 0 018 0v3" stroke="white" stroke-width="2" fill="none"/>
                <circle cx="20" cy="24" r="2" fill="#D4A843"/>
              </svg>
            </div>

            <h2>مرحباً ${name}</h2>
            <p>تلقينا طلباً لإعادة تعيين كلمة المرور الخاصة بحسابك. يرجى النقر على الزر أدناه لإنشاء كلمة مرور جديدة وآمنة:</p>

            <div class="btn-wrap">
              <a href="${resetUrl}" class="btn gold">إعادة تعيين كلمة المرور</a>
            </div>

            <div class="divider"></div>

            <p style="font-size:14px; color:#64748b; margin-bottom:12px;">أو استخدم رمز إعادة التعيين التالي:</p>

            <div style="background:#f8fafc; border:2px dashed #D4A843; border-radius:14px; padding:16px; margin:16px 0; font-family:'Courier New',monospace; font-size:16px; font-weight:700; color:#1A3A6B; letter-spacing:3px; text-align:center; word-break:break-all;">${token}</div>

            <div class="alert amber">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="#92400e" style="vertical-align:middle;margin-left:6px;"><path d="M8 1L1 14h14L8 1zM8 5v4M8 11v.5" stroke="#92400e" stroke-width="1.5" fill="none" stroke-linecap="round"/></svg>
              هذا الرابط صالح لمدة <strong>ساعة واحدة</strong> فقط
            </div>

            <div class="alert red">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="#991b1b" style="vertical-align:middle;margin-left:6px;"><circle cx="8" cy="8" r="7" stroke="#991b1b" stroke-width="1.5" fill="none"/><path d="M8 4v5M8 11v.5" stroke="#991b1b" stroke-width="1.5" stroke-linecap="round"/></svg>
              إذا لم تطلب إعادة تعيين كلمة المرور، يرجى <strong>تغيير كلمة المرور فوراً</strong> للحفاظ على أمان حسابك.
            </div>

            <p style="font-size:13px; color:#94a3b8;">يمكنك أيضاً تجاهل هذه الرسالة إذا لم تطلب إعادة التعيين.</p>
          </div>

          ${getFooter()}
        </div>
      </div>
    </body>
    </html>
  `;
}
