// services/EmailService.js - Email Service for OTP and Notifications
let nodemailer;
try {
  nodemailer = require('nodemailer');
} catch (error) {
  console.error('⚠️  nodemailer not installed. Email functionality disabled.');
}

class EmailService {
  constructor() {
    this.transporter = null;
    if (nodemailer && typeof nodemailer.createTransport === 'function') {
      this.initializeTransporter();
    } else {
      console.warn('⚠️  Nodemailer not available. Email features will be disabled.');
    }
  }

  /**
   * Initialize SMTP transporter with environment variables
   */
  initializeTransporter() {
    try {
      this.transporter = nodemailer.createTransport({
        host: process.env.SMTP_HOST,
        port: parseInt(process.env.SMTP_PORT || '587'),
        secure: process.env.SMTP_SECURE === 'true', // true for 465, false for other ports
        auth: {
          user: process.env.SMTP_USER,
          pass: process.env.SMTP_PASSWORD,
        },
        tls: {
          rejectUnauthorized: process.env.NODE_ENV === 'production'
        }
      });

      console.log('✅ Email service initialized successfully');
    } catch (error) {
      console.error('❌ Email service initialization failed:', error.message);
      console.warn('⚠️  Email functionality will not work. Please configure SMTP settings in .env');
    }
  }

  /**
   * Verify SMTP connection
   */
  async verifyConnection() {
    if (!this.transporter) {
      return { success: false, error: 'Email transporter not initialized' };
    }

    try {
      await this.transporter.verify();
      return { success: true, message: 'SMTP connection verified' };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  /**
   * Send OTP verification email
   */
  async sendOTP(email, otp, firstName = 'User') {
    if (!this.transporter) {
      console.error('Cannot send OTP: Email transporter not initialized');
      return { success: false, error: 'Email service not configured' };
    }

    const htmlContent = this.getOTPEmailTemplate(otp, firstName);

    const mailOptions = {
      from: process.env.SMTP_FROM || 'WakaTraffic <noreply@wakatraffic.ng>',
      to: email,
      subject: 'Verify Your Email - WakaTraffic',
      html: htmlContent,
      text: `Your WakaTraffic verification code is: ${otp}\n\nThis code will expire in 10 minutes.\n\nIf you didn't request this code, please ignore this email.`
    };

    try {
      const info = await this.transporter.sendMail(mailOptions);
      console.log(`✅ OTP email sent to ${email}: ${info.messageId}`);
      return { success: true, messageId: info.messageId };
    } catch (error) {
      console.error(`❌ Failed to send OTP email to ${email}:`, error.message);
      return { success: false, error: error.message };
    }
  }

  /**
   * Send password reset email
   */
  async sendPasswordReset(email, resetToken, firstName = 'User') {
    if (!this.transporter) {
      console.error('Cannot send password reset: Email transporter not initialized');
      return { success: false, error: 'Email service not configured' };
    }

    const resetUrl = `${process.env.APP_URL}/reset-password?token=${resetToken}`;
    const htmlContent = this.getPasswordResetTemplate(resetUrl, firstName);

    const mailOptions = {
      from: process.env.SMTP_FROM || 'WakaTraffic <noreply@wakatraffic.ng>',
      to: email,
      subject: 'Reset Your Password - WakaTraffic',
      html: htmlContent,
      text: `Hi ${firstName},\n\nClick the link below to reset your password:\n${resetUrl}\n\nThis link will expire in 1 hour.\n\nIf you didn't request this, please ignore this email.`
    };

    try {
      const info = await this.transporter.sendMail(mailOptions);
      console.log(`✅ Password reset email sent to ${email}: ${info.messageId}`);
      return { success: true, messageId: info.messageId };
    } catch (error) {
      console.error(`❌ Failed to send password reset email to ${email}:`, error.message);
      return { success: false, error: error.message };
    }
  }

  /**
   * Send welcome email after successful registration
   */
  async sendWelcomeEmail(email, firstName) {
    if (!this.transporter) {
      return { success: false, error: 'Email service not configured' };
    }

    const htmlContent = this.getWelcomeEmailTemplate(firstName);

    const mailOptions = {
      from: process.env.SMTP_FROM || 'WakaTraffic <noreply@wakatraffic.ng>',
      to: email,
      subject: 'Welcome to WakaTraffic!',
      html: htmlContent,
      text: `Welcome to WakaTraffic, ${firstName}!\n\nYour account has been successfully verified.\n\nStart growing your social media presence today!`
    };

    try {
      const info = await this.transporter.sendMail(mailOptions);
      console.log(`✅ Welcome email sent to ${email}: ${info.messageId}`);
      return { success: true, messageId: info.messageId };
    } catch (error) {
      console.error(`❌ Failed to send welcome email to ${email}:`, error.message);
      return { success: false, error: error.message };
    }
  }

  /**
   * Send order confirmation email
   */
  async sendOrderConfirmation(email, orderDetails) {
    if (!this.transporter) {
      return { success: false, error: 'Email service not configured' };
    }

    const htmlContent = this.getOrderConfirmationTemplate(orderDetails);

    const mailOptions = {
      from: process.env.SMTP_FROM || 'WakaTraffic <noreply@wakatraffic.ng>',
      to: email,
      subject: `Order Confirmation #${orderDetails.orderId} - WakaTraffic`,
      html: htmlContent
    };

    try {
      const info = await this.transporter.sendMail(mailOptions);
      return { success: true, messageId: info.messageId };
    } catch (error) {
      console.error(`❌ Failed to send order confirmation to ${email}:`, error.message);
      return { success: false, error: error.message };
    }
  }

  /**
   * OTP Email Template
   */
  getOTPEmailTemplate(otp, firstName) {
    return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Verify Your Email</title>
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f4; padding: 20px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
          <!-- Header -->
          <tr>
            <td style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px 20px; text-align: center;">
              <h1 style="color: #ffffff; margin: 0; font-size: 28px;">WakaTraffic</h1>
              <p style="color: #ffffff; margin: 10px 0 0 0; opacity: 0.9;">Social Media Marketing Platform</p>
            </td>
          </tr>

          <!-- Content -->
          <tr>
            <td style="padding: 40px 30px;">
              <h2 style="color: #333333; margin: 0 0 20px 0; font-size: 24px;">Hi ${firstName}! 👋</h2>
              <p style="color: #666666; line-height: 1.6; margin: 0 0 30px 0;">
                Thank you for registering with WakaTraffic. To complete your registration and verify your email address, please use the verification code below:
              </p>

              <!-- OTP Box -->
              <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td align="center" style="padding: 20px 0;">
                    <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 8px; padding: 20px; display: inline-block;">
                      <p style="color: #ffffff; margin: 0 0 10px 0; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;">Verification Code</p>
                      <p style="color: #ffffff; margin: 0; font-size: 36px; font-weight: bold; letter-spacing: 8px; font-family: 'Courier New', monospace;">${otp}</p>
                    </div>
                  </td>
                </tr>
              </table>

              <p style="color: #666666; line-height: 1.6; margin: 30px 0 0 0;">
                This code will <strong>expire in 10 minutes</strong>. If you didn't request this code, please ignore this email.
              </p>
            </td>
          </tr>

          <!-- Footer -->
          <tr>
            <td style="background-color: #f8f9fa; padding: 30px; text-align: center; border-top: 1px solid #e9ecef;">
              <p style="color: #666666; margin: 0 0 10px 0; font-size: 14px;">
                Need help? Contact us at <a href="mailto:support@wakatraffic.ng" style="color: #667eea; text-decoration: none;">support@wakatraffic.ng</a>
              </p>
              <p style="color: #999999; margin: 0; font-size: 12px;">
                © ${new Date().getFullYear()} WakaTraffic. All rights reserved.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
  }

  /**
   * Password Reset Email Template
   */
  getPasswordResetTemplate(resetUrl, firstName) {
    return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Reset Your Password</title>
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f4; padding: 20px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
          <tr>
            <td style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px 20px; text-align: center;">
              <h1 style="color: #ffffff; margin: 0; font-size: 28px;">WakaTraffic</h1>
            </td>
          </tr>
          <tr>
            <td style="padding: 40px 30px;">
              <h2 style="color: #333333; margin: 0 0 20px 0;">Hi ${firstName},</h2>
              <p style="color: #666666; line-height: 1.6; margin: 0 0 30px 0;">
                We received a request to reset your password. Click the button below to create a new password:
              </p>
              <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td align="center" style="padding: 20px 0;">
                    <a href="${resetUrl}" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #ffffff; padding: 15px 40px; text-decoration: none; border-radius: 5px; display: inline-block; font-weight: bold;">Reset Password</a>
                  </td>
                </tr>
              </table>
              <p style="color: #666666; line-height: 1.6; margin: 30px 0 0 0;">
                This link will expire in <strong>1 hour</strong>. If you didn't request this, please ignore this email.
              </p>
            </td>
          </tr>
          <tr>
            <td style="background-color: #f8f9fa; padding: 30px; text-align: center; border-top: 1px solid #e9ecef;">
              <p style="color: #999999; margin: 0; font-size: 12px;">
                © ${new Date().getFullYear()} WakaTraffic. All rights reserved.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
  }

  /**
   * Welcome Email Template
   */
  getWelcomeEmailTemplate(firstName) {
    return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Welcome to WakaTraffic</title>
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f4; padding: 20px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden;">
          <tr>
            <td style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px 20px; text-align: center;">
              <h1 style="color: #ffffff; margin: 0; font-size: 32px;">Welcome to WakaTraffic! 🎉</h1>
            </td>
          </tr>
          <tr>
            <td style="padding: 40px 30px;">
              <h2 style="color: #333333; margin: 0 0 20px 0;">Hi ${firstName}!</h2>
              <p style="color: #666666; line-height: 1.6;">
                Your account has been successfully verified. You're now ready to start growing your social media presence!
              </p>
              <p style="color: #666666; line-height: 1.6;">
                With WakaTraffic, you can boost your followers, likes, views, and engagement across all major social media platforms.
              </p>
              <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td align="center" style="padding: 30px 0;">
                    <a href="${process.env.APP_URL}/dashboard" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #ffffff; padding: 15px 40px; text-decoration: none; border-radius: 5px; display: inline-block; font-weight: bold;">Go to Dashboard</a>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          <tr>
            <td style="background-color: #f8f9fa; padding: 30px; text-align: center;">
              <p style="color: #999999; margin: 0; font-size: 12px;">
                © ${new Date().getFullYear()} WakaTraffic. All rights reserved.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
  }

  /**
   * Order Confirmation Email Template
   */
  getOrderConfirmationTemplate(orderDetails) {
    return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Order Confirmation</title>
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f4; padding: 20px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden;">
          <tr>
            <td style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px 20px; text-align: center;">
              <h1 style="color: #ffffff; margin: 0; font-size: 28px;">Order Confirmed! ✓</h1>
            </td>
          </tr>
          <tr>
            <td style="padding: 40px 30px;">
              <h2 style="color: #333333; margin: 0 0 20px 0;">Order #${orderDetails.orderId}</h2>
              <p style="color: #666666; line-height: 1.6;">
                Your order has been placed successfully and is now being processed.
              </p>
              <table width="100%" cellpadding="10" style="margin: 20px 0; border: 1px solid #e9ecef; border-radius: 5px;">
                <tr>
                  <td style="color: #666666; padding: 10px;"><strong>Service:</strong></td>
                  <td style="color: #333333; padding: 10px;">${orderDetails.serviceName}</td>
                </tr>
                <tr style="background-color: #f8f9fa;">
                  <td style="color: #666666; padding: 10px;"><strong>Quantity:</strong></td>
                  <td style="color: #333333; padding: 10px;">${orderDetails.quantity}</td>
                </tr>
                <tr>
                  <td style="color: #666666; padding: 10px;"><strong>Amount:</strong></td>
                  <td style="color: #333333; padding: 10px;">₦${orderDetails.charge}</td>
                </tr>
                <tr style="background-color: #f8f9fa;">
                  <td style="color: #666666; padding: 10px;"><strong>Status:</strong></td>
                  <td style="color: #333333; padding: 10px;"><span style="background-color: #ffc107; color: #000; padding: 3px 10px; border-radius: 3px; font-size: 12px;">${orderDetails.status}</span></td>
                </tr>
              </table>
              <p style="color: #666666; line-height: 1.6;">
                You can track your order status from your dashboard.
              </p>
            </td>
          </tr>
          <tr>
            <td style="background-color: #f8f9fa; padding: 30px; text-align: center;">
              <p style="color: #999999; margin: 0; font-size: 12px;">
                © ${new Date().getFullYear()} WakaTraffic. All rights reserved.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
  }
}

// Export singleton instance
module.exports = new EmailService();
