/**
 * Email Service
 *
 * Handles email notifications (SendGrid integration)
 */

// @ts-ignore - @sendgrid/mail types not available
import sgMail from '@sendgrid/mail';
import { config } from '../config';
import { logger } from '../utils/logger';

// Initialize SendGrid
if (config.sendgridApiKey) {
  sgMail.setApiKey(config.sendgridApiKey);
} else if (config.nodeEnv === 'production') {
  logger.warn('SendGrid API key not configured - emails will fail in production');
}

/**
 * Send welcome email
 */
export async function sendWelcomeEmail(email: string, name: string): Promise<boolean> {
  try {
    if (!config.sendgridApiKey) {
      logger.warn('SendGrid not configured, skipping welcome email', { email });
      return false;
    }

    const msg = {
      to: email,
      from: {
        email: config.sendgridFromEmail,
        name: config.sendgridFromName,
      },
      subject: 'Welcome to TranslatePress.zone!',
      text: `Hello ${name},\n\nWelcome to TranslatePress.zone! We're excited to have you on board.`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>Welcome to TranslatePress.zone!</h2>
          <p>Hello ${name},</p>
          <p>We're excited to have you on board. You can now use our powerful translation API to localize your content.</p>
          <p>Get started by:</p>
          <ul>
            <li>Generating your API key</li>
            <li>Installing the WordPress plugin</li>
            <li>Starting your first translation</li>
          </ul>
          <a href="${config.frontendUrl}/dashboard" style="display: inline-block; background-color: #3b82f6; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 20px 0;">
            Go to Dashboard
          </a>
        </div>
      `,
    };

    await sgMail.send(msg);
    logger.info('Welcome email sent', { email, name });
    return true;
  } catch (error) {
    logger.error('Failed to send welcome email', { error, email });
    return false;
  }
}

/**
 * Send email verification
 */
export async function sendVerificationEmail(email: string, token: string): Promise<boolean> {
  try {
    if (!config.sendgridApiKey) {
      logger.warn('SendGrid not configured, skipping verification email', { email });
      logger.info(`Verification token: ${token}`, { email });
      return false;
    }

    const verificationUrl = `${config.frontendUrl}/verify-email?token=${token}`;

    const msg = {
      to: email,
      from: {
        email: config.sendgridFromEmail,
        name: config.sendgridFromName,
      },
      subject: 'Verify your email address',
      text: `Please verify your email by clicking: ${verificationUrl}`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>Verify Your Email Address</h2>
          <p>Thank you for signing up! Please click the button below to verify your email address:</p>
          <a href="${verificationUrl}" style="display: inline-block; background-color: #3b82f6; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 20px 0;">
            Verify Email
          </a>
          <p>Or copy and paste this link into your browser:</p>
          <p style="color: #666; font-size: 14px; word-break: break-all;">${verificationUrl}</p>
          <p style="color: #999; font-size: 12px; margin-top: 30px;">
            If you didn't create an account, please ignore this email.
          </p>
        </div>
      `,
    };

    await sgMail.send(msg);
    logger.info('Verification email sent', { email, verificationUrl });
    return true;
  } catch (error) {
    logger.error('Failed to send verification email', { error, email });
    throw new Error('Failed to send verification email');
  }
}

/**
 * Send password reset email
 */
export async function sendPasswordResetEmail(email: string, token: string): Promise<boolean> {
  try {
    if (!config.sendgridApiKey) {
      logger.warn('SendGrid not configured, skipping password reset email', { email });
      logger.info(`Reset token: ${token}`, { email });
      return false;
    }

    const resetUrl = `${config.frontendUrl}/reset-password?token=${token}`;

    const msg = {
      to: email,
      from: {
        email: config.sendgridFromEmail,
        name: config.sendgridFromName,
      },
      subject: 'Reset your password',
      text: `Reset your password by clicking: ${resetUrl}\n\nThis link expires in 1 hour.`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>Reset Your Password</h2>
          <p>We received a request to reset your password. Click the button below to create a new password:</p>
          <a href="${resetUrl}" style="display: inline-block; background-color: #3b82f6; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 20px 0;">
            Reset Password
          </a>
          <p>Or copy and paste this link into your browser:</p>
          <p style="color: #666; font-size: 14px; word-break: break-all;">${resetUrl}</p>
          <p style="color: #dc2626; font-size: 14px; margin-top: 20px;">
            ⏰ This link expires in 1 hour.
          </p>
          <p style="color: #999; font-size: 12px; margin-top: 30px;">
            If you didn't request a password reset, please ignore this email or contact support if you're concerned.
          </p>
        </div>
      `,
    };

    await sgMail.send(msg);
    logger.info('Password reset email sent', { email, resetUrl });
    return true;
  } catch (error) {
    logger.error('Failed to send password reset email', { error, email });
    throw new Error('Failed to send password reset email');
  }
}

/**
 * Send low credit warning
 */
export async function sendLowCreditWarning(email: string, creditsRemaining: number): Promise<boolean> {
  try {
    if (!config.sendgridApiKey) {
      logger.warn('SendGrid not configured, skipping low credit warning', { email });
      return false;
    }

    const msg = {
      to: email,
      from: {
        email: config.sendgridFromEmail,
        name: config.sendgridFromName,
      },
      subject: '⚠️ Low credit balance',
      text: `Your credit balance is low: ${creditsRemaining.toLocaleString()} tokens remaining.`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>⚠️ Low Credit Balance</h2>
          <p>Your credit balance is running low.</p>
          <div style="background-color: #fef3c7; border-left: 4px solid #f59e0b; padding: 16px; border-radius: 4px; margin: 20px 0;">
            <p style="margin: 0; font-size: 18px; font-weight: bold; color: #92400e;">
              ${creditsRemaining.toLocaleString()} tokens remaining
            </p>
          </div>
          <p>To ensure uninterrupted service, consider upgrading your plan or purchasing additional credits.</p>
          <a href="${config.frontendUrl}/account/subscription" style="display: inline-block; background-color: #3b82f6; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 20px 0;">
            Upgrade Plan
          </a>
        </div>
      `,
    };

    await sgMail.send(msg);
    logger.info('Low credit warning sent', { email, creditsRemaining });
    return true;
  } catch (error) {
    logger.error('Failed to send low credit warning', { error, email });
    return false;
  }
}

/**
 * Send subscription receipt
 */
export async function sendSubscriptionReceipt(
  email: string,
  amount: number,
  planTier: string
): Promise<boolean> {
  try {
    if (!config.sendgridApiKey) {
      logger.warn('SendGrid not configured, skipping subscription receipt', { email });
      return false;
    }

    const msg = {
      to: email,
      from: {
        email: config.sendgridFromEmail,
        name: config.sendgridFromName,
      },
      subject: `Payment receipt - ${planTier} plan`,
      text: `Thank you for your payment of $${amount.toFixed(2)} for the ${planTier} plan.`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>Payment Receipt</h2>
          <p>Thank you for your payment! Here are your receipt details:</p>
          <div style="background-color: #f3f4f6; padding: 20px; border-radius: 8px; margin: 20px 0;">
            <table style="width: 100%; border-collapse: collapse;">
              <tr>
                <td style="padding: 8px 0; color: #64748b;">Plan:</td>
                <td style="padding: 8px 0; text-align: right; font-weight: bold; text-transform: capitalize;">${planTier}</td>
              </tr>
              <tr>
                <td style="padding: 8px 0; color: #64748b;">Amount:</td>
                <td style="padding: 8px 0; text-align: right; font-weight: bold;">$${amount.toFixed(2)}</td>
              </tr>
              <tr>
                <td style="padding: 8px 0; color: #64748b;">Date:</td>
                <td style="padding: 8px 0; text-align: right;">${new Date().toLocaleDateString()}</td>
              </tr>
            </table>
          </div>
          <p>Your credits have been added to your account and you can start translating right away.</p>
          <a href="${config.frontendUrl}/dashboard" style="display: inline-block; background-color: #10b981; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 20px 0;">
            Go to Dashboard
          </a>
          <p style="color: #999; font-size: 12px; margin-top: 30px;">
            Questions? Contact us at support@translate.press.zone
          </p>
        </div>
      `,
    };

    await sgMail.send(msg);
    logger.info('Subscription receipt sent', { email, amount, planTier });
    return true;
  } catch (error) {
    logger.error('Failed to send subscription receipt', { error, email });
    return false;
  }
}

/**
 * Send job completion notification
 */
export async function sendJobCompletionEmail(
  email: string,
  jobId: string,
  sourceLang: string,
  targetLang: string
): Promise<boolean> {
  try {
    if (!config.sendgridApiKey) {
      logger.warn('SendGrid not configured, skipping job completion email', { email });
      return false;
    }

    const msg = {
      to: email,
      from: {
        email: config.sendgridFromEmail,
        name: config.sendgridFromName,
      },
      subject: 'Your translation is ready',
      text: `Your translation job (${sourceLang} → ${targetLang}) is complete.`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>✓ Translation Complete</h2>
          <p>Your translation job is ready!</p>
          <div style="background-color: #d1fae5; padding: 16px; border-radius: 8px; margin: 20px 0;">
            <p style="margin: 0;"><strong>Language Pair:</strong> ${sourceLang.toUpperCase()} → ${targetLang.toUpperCase()}</p>
            <p style="margin: 8px 0 0 0;"><strong>Job ID:</strong> <code>${jobId.substring(0, 16)}...</code></p>
          </div>
          <p>The translated content is now available in your WordPress site or via the API.</p>
        </div>
      `,
    };

    await sgMail.send(msg);
    logger.info('Job completion email sent', { email, jobId });
    return true;
  } catch (error) {
    logger.error('Failed to send job completion email', { email, jobId, error });
    return false;
  }
}
