import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Mailgun from 'mailgun.js';
import formData from 'form-data';

export interface EmailOptions {
  to: string;
  subject: string;
  html: string;
  text?: string;
}

export interface PasswordResetEmailData {
  userName: string;
  resetLink: string;
  expiresIn: string;
}

export interface EmailVerificationData {
  userName: string;
  verificationLink: string;
}

@Injectable()
export class EmailService {
  private readonly logger = new Logger(EmailService.name);
  private mailgunClient: any;
  private readonly fromEmail: string;
  private readonly fromName: string;
  private readonly appUrl: string;
  private readonly mailgunDomain: string;

  constructor(private configService: ConfigService) {
    const mailgunApiKey = this.configService.get<string>('MAILGUN_API_KEY');
    const mailgunRegion = this.configService.get<string>(
      'MAILGUN_REGION',
      'us',
    ); // 'us' or 'eu'
    this.mailgunDomain = this.configService.get<string>('MAILGUN_DOMAIN', '');
    this.fromEmail = this.configService.get<string>(
      'EMAIL_FROM',
      'noreply@maternal-app.com',
    );
    this.fromName = this.configService.get<string>(
      'EMAIL_FROM_NAME',
      'Maternal App',
    );
    this.appUrl = this.configService.get<string>(
      'APP_URL',
      'http://localhost:3030',
    );

    // Initialize Mailgun client
    if (mailgunApiKey && this.mailgunDomain) {
      const mailgun = new Mailgun(formData);
      this.mailgunClient = mailgun.client({
        username: 'api',
        key: mailgunApiKey,
        url:
          mailgunRegion === 'eu'
            ? 'https://api.eu.mailgun.net'
            : 'https://api.mailgun.net',
      });
      this.logger.log(
        `Mailgun initialized for ${mailgunRegion.toUpperCase()} region`,
      );
    } else {
      this.logger.warn(
        'Mailgun not configured - emails will be logged but not sent',
      );
    }
  }

  /**
   * Send a generic email
   */
  async sendEmail(options: EmailOptions): Promise<void> {
    const { to, subject, html, text } = options;

    if (!this.mailgunClient) {
      this.logger.warn(
        `[EMAIL NOT SENT - No Mailgun Config] To: ${to}, Subject: ${subject}`,
      );
      this.logger.debug(`Email content: ${text || html.substring(0, 200)}...`);
      return;
    }

    try {
      const messageData = {
        from: `${this.fromName} <${this.fromEmail}>`,
        to,
        subject,
        html,
        text: text || this.stripHtml(html),
      };

      await this.mailgunClient.messages.create(this.mailgunDomain, messageData);
      this.logger.log(`Email sent successfully to ${to}: ${subject}`);
    } catch (error) {
      this.logger.error(
        `Failed to send email to ${to}: ${error.message}`,
        error.stack,
      );
      throw error;
    }
  }

  /**
   * Send password reset email
   */
  async sendPasswordResetEmail(
    to: string,
    data: PasswordResetEmailData,
  ): Promise<void> {
    const subject = 'Reset Your Maternal App Password';
    const html = this.getPasswordResetEmailTemplate(data);

    await this.sendEmail({ to, subject, html });
  }

  /**
   * Send email verification email
   */
  async sendEmailVerificationEmail(
    to: string,
    data: EmailVerificationData,
  ): Promise<void> {
    const subject = 'Verify Your Maternal App Email';
    const html = this.getEmailVerificationTemplate(data);

    await this.sendEmail({ to, subject, html });
  }

  /**
   * Send welcome email after successful registration
   */
  async sendWelcomeEmail(to: string, userName: string): Promise<void> {
    const subject = 'Welcome to Maternal App! 🎉';
    const html = this.getWelcomeEmailTemplate(userName);

    await this.sendEmail({ to, subject, html });
  }

  /**
   * Password reset email template
   */
  private getPasswordResetEmailTemplate(data: PasswordResetEmailData): string {
    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>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background-color: #f5f5f5; }
    .container { max-width: 600px; margin: 40px auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
    .header { background: linear-gradient(135deg, #FFB5A0 0%, #FF8B7D 100%); padding: 40px 20px; text-align: center; color: white; }
    .header h1 { margin: 0; font-size: 28px; font-weight: 600; }
    .content { padding: 40px 30px; }
    .content p { margin: 0 0 20px 0; font-size: 16px; }
    .button { display: inline-block; padding: 14px 32px; background: #FF8B7D; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 16px; margin: 20px 0; }
    .button:hover { background: #FF7B6D; }
    .info-box { background: #FFF5F5; border-left: 4px solid #FFB5A0; padding: 15px; margin: 20px 0; border-radius: 4px; }
    .footer { background: #f9f9f9; padding: 20px 30px; text-align: center; font-size: 14px; color: #666; }
    .footer a { color: #FF8B7D; text-decoration: none; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>Reset Your Password</h1>
    </div>
    <div class="content">
      <p>Hi ${data.userName},</p>
      <p>We received a request to reset your password for your Maternal App account. Click the button below to create a new password:</p>
      <div style="text-align: center;">
        <a href="${data.resetLink}" class="button">Reset Password</a>
      </div>
      <div class="info-box">
        <strong>⏱️ This link expires in ${data.expiresIn}</strong><br>
        If you didn't request a password reset, please ignore this email. Your password will remain unchanged.
      </div>
      <p>If the button doesn't work, copy and paste this link into your browser:</p>
      <p style="word-break: break-all; color: #666; font-size: 14px;">${data.resetLink}</p>
      <p style="margin-top: 30px;">Best regards,<br>The Maternal App Team</p>
    </div>
    <div class="footer">
      <p>If you have any questions, contact us at <a href="mailto:support@maternal-app.com">support@maternal-app.com</a></p>
      <p>© ${new Date().getFullYear()} Maternal App. All rights reserved.</p>
    </div>
  </div>
</body>
</html>
    `.trim();
  }

  /**
   * Email verification template
   */
  private getEmailVerificationTemplate(data: EmailVerificationData): string {
    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>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background-color: #f5f5f5; }
    .container { max-width: 600px; margin: 40px auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
    .header { background: linear-gradient(135deg, #FFB5A0 0%, #FF8B7D 100%); padding: 40px 20px; text-align: center; color: white; }
    .header h1 { margin: 0; font-size: 28px; font-weight: 600; }
    .content { padding: 40px 30px; }
    .content p { margin: 0 0 20px 0; font-size: 16px; }
    .button { display: inline-block; padding: 14px 32px; background: #FF8B7D; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 16px; margin: 20px 0; }
    .button:hover { background: #FF7B6D; }
    .info-box { background: #E8F5E9; border-left: 4px solid #4CAF50; padding: 15px; margin: 20px 0; border-radius: 4px; }
    .footer { background: #f9f9f9; padding: 20px 30px; text-align: center; font-size: 14px; color: #666; }
    .footer a { color: #FF8B7D; text-decoration: none; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>Verify Your Email 📧</h1>
    </div>
    <div class="content">
      <p>Hi ${data.userName},</p>
      <p>Thank you for signing up for Maternal App! To complete your registration and access all features, please verify your email address by clicking the button below:</p>
      <div style="text-align: center;">
        <a href="${data.verificationLink}" class="button">Verify Email</a>
      </div>
      <div class="info-box">
        <strong>✅ Why verify?</strong><br>
        Email verification helps us ensure your account security and enables us to send you important updates about your child's activities and milestones.
      </div>
      <p>If the button doesn't work, copy and paste this link into your browser:</p>
      <p style="word-break: break-all; color: #666; font-size: 14px;">${data.verificationLink}</p>
      <p style="margin-top: 30px;">Welcome to the Maternal App family! 🎉<br>The Maternal App Team</p>
    </div>
    <div class="footer">
      <p>If you didn't create an account, you can safely ignore this email.</p>
      <p>Questions? Contact us at <a href="mailto:support@maternal-app.com">support@maternal-app.com</a></p>
      <p>© ${new Date().getFullYear()} Maternal App. All rights reserved.</p>
    </div>
  </div>
</body>
</html>
    `.trim();
  }

  /**
   * Welcome email template
   */
  private getWelcomeEmailTemplate(userName: string): string {
    return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Welcome to Maternal App</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background-color: #f5f5f5; }
    .container { max-width: 600px; margin: 40px auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
    .header { background: linear-gradient(135deg, #FFB5A0 0%, #FF8B7D 100%); padding: 40px 20px; text-align: center; color: white; }
    .header h1 { margin: 0; font-size: 28px; font-weight: 600; }
    .content { padding: 40px 30px; }
    .content p { margin: 0 0 20px 0; font-size: 16px; }
    .feature-box { background: #FFF5F5; padding: 20px; margin: 15px 0; border-radius: 6px; border-left: 4px solid #FFB5A0; }
    .feature-box h3 { margin: 0 0 10px 0; color: #FF8B7D; font-size: 18px; }
    .button { display: inline-block; padding: 14px 32px; background: #FF8B7D; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 16px; margin: 20px 0; }
    .footer { background: #f9f9f9; padding: 20px 30px; text-align: center; font-size: 14px; color: #666; }
    .footer a { color: #FF8B7D; text-decoration: none; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>Welcome to Maternal App! 🎉</h1>
    </div>
    <div class="content">
      <p>Hi ${userName},</p>
      <p>We're thrilled to have you join the Maternal App family! Our mission is to help you track and understand your child's development, reduce your mental load, and provide AI-powered parenting support whenever you need it.</p>

      <div class="feature-box">
        <h3>📊 Track Activities</h3>
        <p>Easily log feeding, sleep, diaper changes, and more with our intuitive interface.</p>
      </div>

      <div class="feature-box">
        <h3>🤖 AI Parenting Assistant</h3>
        <p>Get personalized insights and answers to your parenting questions 24/7.</p>
      </div>

      <div class="feature-box">
        <h3>👨‍👩‍👧 Family Sync</h3>
        <p>Keep everyone in the loop with real-time activity updates across all devices.</p>
      </div>

      <div style="text-align: center;">
        <a href="${this.appUrl}" class="button">Get Started</a>
      </div>

      <p style="margin-top: 30px;">If you have any questions or need help getting started, our support team is here for you!</p>
      <p>Happy parenting! 💕<br>The Maternal App Team</p>
    </div>
    <div class="footer">
      <p>Questions? Contact us at <a href="mailto:support@maternal-app.com">support@maternal-app.com</a></p>
      <p>© ${new Date().getFullYear()} Maternal App. All rights reserved.</p>
    </div>
  </div>
</body>
</html>
    `.trim();
  }

  /**
   * Strip HTML tags for plain text version
   */
  private stripHtml(html: string): string {
    return html
      .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
      .replace(/<[^>]+>/g, '')
      .replace(/\s+/g, ' ')
      .trim();
  }
}
