import nodemailer from 'nodemailer';
import { config } from '../config';
import { createLogger } from './logger';

const logger = createLogger('Email');

// SMTP transporter — used for Brevo and SendGrid
function createSmtpTransporter() {
  return nodemailer.createTransport({
    host: config.email.host,
    port: config.email.port,
    secure: config.email.port === 465,
    auth: {
      user: config.email.user,
      pass: config.email.pass,
    },
  });
}

// Mailjet SMTP relay transporter
function createMailjetTransporter() {
  return nodemailer.createTransport({
    host: 'in-v3.mailjet.com',
    port: 587,
    secure: false,
    auth: {
      user: config.email.mailjetApiKey,
      pass: config.email.mailjetApiSecret,
    },
  });
}

function createTransporter() {
  if (config.email.provider === 'mailjet') {
    return createMailjetTransporter();
  }
  return createSmtpTransporter();
}

/**
 * Send an account verification email.
 * If SMTP is not configured, logs the verification URL to the console (dev mode).
 */
export async function sendVerificationEmail(email: string, token: string): Promise<void> {
  const verifyUrl = `${config.email.appUrl}/en-GB/verify-email?token=${token}`;

  // Always log in non-production so devs can verify the flow without a working SMTP
  if (process.env.NODE_ENV !== 'production') {
    console.log('\n─────────────────────────────────────────');
    console.log('  [DEV] Verification email for:', email);
    console.log('  Verify URL:', verifyUrl);
    console.log('─────────────────────────────────────────\n');
  }

  const isMailjet = config.email.provider === 'mailjet';
  const credsMissing = isMailjet
    ? !config.email.mailjetApiKey || !config.email.mailjetApiSecret
    : !config.email.user || !config.email.pass;

  if (credsMissing) {
    logger.warn(`${isMailjet ? 'Mailjet' : 'SMTP'} not configured — skipping email send`);
    return;
  }

  const transporter = createTransporter();

  logger.info('Attempting to send verification email', {
    email,
    provider: config.email.provider,
    smtp: isMailjet
      ? { host: 'in-v3.mailjet.com', port: 587 }
      : { host: config.email.host, port: config.email.port },
  });

  try {
    const info = await transporter.sendMail({
      from: `"CahooTravel" <${config.email.from}>`,
      to: email,
      subject: 'Verify your CahooTravel account',
      html: `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f9fafb; margin: 0; padding: 40px 0;">
  <table align="center" width="100%" cellpadding="0" cellspacing="0" style="max-width: 520px; margin: 0 auto;">
    <tr>
      <td style="background: #fff; border-radius: 12px; padding: 40px; box-shadow: 0 1px 3px rgba(0,0,0,0.08);">
        <h1 style="color: #4C1D95; font-size: 24px; margin: 0 0 8px;">Welcome to CahooTravel!</h1>
        <p style="color: #6b7280; font-size: 15px; margin: 0 0 24px; line-height: 1.6;">
          Thanks for creating an account. Please verify your email address to get started finding hidden travel deals.
        </p>
        <a href="${verifyUrl}"
           style="display: inline-block; background: #4C1D95; color: #fff; text-decoration: none;
                  padding: 12px 28px; border-radius: 8px; font-weight: 600; font-size: 15px;">
          Verify my email
        </a>
        <p style="color: #9ca3af; font-size: 13px; margin: 24px 0 0; line-height: 1.6;">
          This link expires in 24 hours. If you didn't create an account you can safely ignore this email.
        </p>
        <hr style="border: none; border-top: 1px solid #f3f4f6; margin: 24px 0;" />
        <p style="color: #d1d5db; font-size: 12px; margin: 0;">
          If the button above doesn't work, copy and paste this URL into your browser:<br />
          <a href="${verifyUrl}" style="color: #4C1D95; word-break: break-all;">${verifyUrl}</a>
        </p>
      </td>
    </tr>
  </table>
</body>
</html>
      `.trim(),
      text: `Welcome to CahooTravel!\n\nPlease verify your email by visiting:\n${verifyUrl}\n\nThis link expires in 24 hours.`,
    });
    logger.info('Verification email sent', {
      email,
      messageId: info.messageId,
      response: info.response,
    });
  } catch (err) {
    logger.error('Verification email rejected by SMTP', {
      email,
      error: err instanceof Error ? err.message : String(err),
    });
    throw err;
  }
}

/**
 * Send a password reset email with a 30-minute expiry link.
 * Falls back to console logging in non-production environments.
 */
export async function sendPasswordResetEmail(email: string, token: string): Promise<void> {
  const resetUrl = `${config.email.appUrl}/en-GB/reset-password?token=${token}`;

  if (process.env.NODE_ENV !== 'production') {
    console.log('\n─────────────────────────────────────────');
    console.log('  [DEV] Password reset email for:', email);
    console.log('  Reset URL:', resetUrl);
    console.log('─────────────────────────────────────────\n');
  }

  const isMailjet = config.email.provider === 'mailjet';
  const credsMissing = isMailjet
    ? !config.email.mailjetApiKey || !config.email.mailjetApiSecret
    : !config.email.user || !config.email.pass;

  if (credsMissing) {
    logger.warn(`${isMailjet ? 'Mailjet' : 'SMTP'} not configured — skipping password reset email send`);
    return;
  }

  const transporter = createTransporter();

  logger.info('Attempting to send password reset email', {
    email,
    provider: config.email.provider,
  });

  try {
    const info = await transporter.sendMail({
      from: `"CahooTravel" <${config.email.from}>`,
      to: email,
      subject: 'Reset your CahooTravel password',
      html: `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f9fafb; margin: 0; padding: 40px 0;">
  <table align="center" width="100%" cellpadding="0" cellspacing="0" style="max-width: 520px; margin: 0 auto;">
    <tr>
      <td style="background: #fff; border-radius: 12px; padding: 40px; box-shadow: 0 1px 3px rgba(0,0,0,0.08);">
        <h1 style="color: #4C1D95; font-size: 24px; margin: 0 0 8px;">Reset your password</h1>
        <p style="color: #6b7280; font-size: 15px; margin: 0 0 24px; line-height: 1.6;">
          We received a request to reset the password for your CahooTravel account. Click the button below to choose a new password.
        </p>
        <a href="${resetUrl}"
           style="display: inline-block; background: #4C1D95; color: #fff; text-decoration: none;
                  padding: 12px 28px; border-radius: 8px; font-weight: 600; font-size: 15px;">
          Reset my password
        </a>
        <p style="color: #9ca3af; font-size: 13px; margin: 24px 0 0; line-height: 1.6;">
          This link expires in 30 minutes. If you didn't request a password reset you can safely ignore this email — your password will not change.
        </p>
        <hr style="border: none; border-top: 1px solid #f3f4f6; margin: 24px 0;" />
        <p style="color: #d1d5db; font-size: 12px; margin: 0;">
          If the button above doesn't work, copy and paste this URL into your browser:<br />
          <a href="${resetUrl}" style="color: #4C1D95; word-break: break-all;">${resetUrl}</a>
        </p>
      </td>
    </tr>
  </table>
</body>
</html>
      `.trim(),
      text: `Reset your CahooTravel password\n\nClick the link below to choose a new password:\n${resetUrl}\n\nThis link expires in 30 minutes. If you didn't request this, you can safely ignore this email.`,
    });
    logger.info('Password reset email sent', {
      email,
      messageId: info.messageId,
      response: info.response,
    });
  } catch (err) {
    logger.error('Password reset email rejected by SMTP', {
      email,
      error: err instanceof Error ? err.message : String(err),
    });
    throw err;
  }
}

const CONTACT_INBOX = 'info@cahootravel.com';

interface ContactFormEmailOptions {
  firstName: string;
  lastName: string;
  email: string;
  phone?: string;
  company?: string;
  country?: string;
  companySize?: string;
  potentialUsers?: string;
  helpWith?: string;
  product?: string;
  message: string;
}

/**
 * Send a contact-form submission to info@cahootravel.com.
 * Reply-To is set to the submitter's email for easy follow-up.
 */
export async function sendContactFormEmail(data: ContactFormEmailOptions): Promise<void> {
  const isMailjet = config.email.provider === 'mailjet';
  const credsMissing = isMailjet
    ? !config.email.mailjetApiKey || !config.email.mailjetApiSecret
    : !config.email.user || !config.email.pass;

  if (credsMissing) {
    logger.warn(`${isMailjet ? 'Mailjet' : 'SMTP'} not configured — skipping contact form email`);
    return;
  }

  const transporter = createTransporter();
  const esc = (s: string) =>
    s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

  const row = (label: string, value: string | undefined) =>
    value
      ? `<tr><td style="color:#374151;font-size:13px;padding:4px 0;"><strong>${label}:</strong> ${esc(value)}</td></tr>`
      : '';

  const sharedStyles = `font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#f9fafb;margin:0;padding:40px 0;`;
  const cardStyles = `background:#fff;border-radius:12px;padding:40px;box-shadow:0 1px 3px rgba(0,0,0,0.08);`;

  const inboxHtml = `
<!DOCTYPE html><html><head><meta charset="utf-8"/></head>
<body style="${sharedStyles}">
  <table align="center" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;margin:0 auto;">
    <tr><td style="${cardStyles}">
      <h2 style="color:#4C1D95;font-size:18px;margin:0 0 16px;">New contact form submission</h2>
      <table width="100%" cellpadding="0" cellspacing="0" style="background:#f9fafb;border-radius:8px;padding:16px;margin-bottom:20px;">
        ${row('Name', `${data.firstName} ${data.lastName}`)}
        ${row('Email', data.email)}
        ${row('Phone', data.phone)}
        ${row('Company', data.company)}
        ${row('Country', data.country)}
        ${row('Company size', data.companySize)}
        ${row('Potential users', data.potentialUsers)}
        ${row('Help with', data.helpWith)}
        ${row('Product interest', data.product)}
      </table>
      <p style="color:#374151;font-size:14px;line-height:1.7;white-space:pre-wrap;">${esc(data.message)}</p>
    </td></tr>
  </table>
</body></html>`.trim();

  const inboxText = [
    `New contact form submission`,
    `Name: ${data.firstName} ${data.lastName}`,
    `Email: ${data.email}`,
    data.phone ? `Phone: ${data.phone}` : '',
    data.company ? `Company: ${data.company}` : '',
    data.country ? `Country: ${data.country}` : '',
    data.companySize ? `Company size: ${data.companySize}` : '',
    data.potentialUsers ? `Potential users: ${data.potentialUsers}` : '',
    data.helpWith ? `Help with: ${data.helpWith}` : '',
    data.product ? `Product interest: ${data.product}` : '',
    `\n${data.message}`,
  ].filter(Boolean).join('\n');

  // ── 1. Notification to inbox ──────────────────────────────────────────────
  await transporter.sendMail({
    from: `"CahooTravel" <${config.email.from}>`,
    to: CONTACT_INBOX,
    replyTo: data.email,
    subject: `New contact form submission from ${data.firstName} ${data.lastName}`,
    html: inboxHtml,
    text: inboxText,
  });

  logger.info('Contact form email sent to inbox', { from: data.email, to: CONTACT_INBOX });

  // ── 2. Confirmation copy to the sender (disabled for now) ───────────────
  // await transporter.sendMail({
  //   from: `"CahooTravel" <${config.email.from}>`,
  //   to: data.email,
  //   subject: `We received your message, ${data.firstName}`,
  //   html: `...`,
  //   text: `Hi ${data.firstName}, we've received your message and will be in touch soon.`,
  // });
  // logger.info('Contact form confirmation sent to sender', { to: data.email });
}

interface SupportTicketEmailOptions {
  ticketId: string;
  userEmail: string;
  category: string;
  subject: string;
  message: string;
}

/**
 * Send a support ticket confirmation to the user and a notification to the
 * support inbox (config.email.from). Uses the configured Mailjet or SMTP provider.
 */
export async function sendSupportTicketEmail({
  ticketId,
  userEmail,
  category,
  subject,
  message,
}: SupportTicketEmailOptions): Promise<void> {
  const isMailjet = config.email.provider === 'mailjet';
  const credsMissing = isMailjet
    ? !config.email.mailjetApiKey || !config.email.mailjetApiSecret
    : !config.email.user || !config.email.pass;

  if (credsMissing) {
    logger.warn(`${isMailjet ? 'Mailjet' : 'SMTP'} not configured — skipping support ticket email`);
    return;
  }

  const transporter = createTransporter();
  const supportInbox = config.email.from; // e.g. info@cahootravel.com

  // Escape user-supplied content for safe HTML inclusion
  const esc = (s: string) =>
    s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

  const sharedStyles = `font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#f9fafb;margin:0;padding:40px 0;`;
  const cardStyles = `background:#fff;border-radius:12px;padding:40px;box-shadow:0 1px 3px rgba(0,0,0,0.08);`;

  // ── 1. Confirmation to the user ──────────────────────────────────────────
  try {
    await transporter.sendMail({
      from: `"CahooTravel Support" <${supportInbox}>`,
      to: userEmail,
      subject: `[${ticketId}] We received your message`,
      html: `
<!DOCTYPE html><html><head><meta charset="utf-8"/></head>
<body style="${sharedStyles}">
  <table align="center" width="100%" cellpadding="0" cellspacing="0" style="max-width:520px;margin:0 auto;">
    <tr><td style="${cardStyles}">
      <h1 style="color:#4C1D95;font-size:22px;margin:0 0 8px;">We've got your message!</h1>
      <p style="color:#6b7280;font-size:15px;margin:0 0 20px;line-height:1.6;">
        Thank you for reaching out. Our team will get back to you as soon as possible.
      </p>
      <table width="100%" cellpadding="0" cellspacing="0" style="background:#f9fafb;border-radius:8px;padding:16px;margin-bottom:20px;">
        <tr><td style="color:#6b7280;font-size:13px;padding:4px 0;"><strong style="color:#374151;">Ticket ID:</strong> ${esc(ticketId)}</td></tr>
        <tr><td style="color:#6b7280;font-size:13px;padding:4px 0;"><strong style="color:#374151;">Category:</strong> ${esc(category)}</td></tr>
        <tr><td style="color:#6b7280;font-size:13px;padding:4px 0;"><strong style="color:#374151;">Subject:</strong> ${esc(subject)}</td></tr>
      </table>
      <p style="color:#9ca3af;font-size:13px;margin:0;line-height:1.6;">
        If you have more details to add, simply reply to this email and include your ticket ID.
      </p>
    </td></tr>
  </table>
</body></html>`.trim(),
      text: `Ticket received: ${ticketId}\nCategory: ${category}\nSubject: ${subject}\n\nWe'll be in touch soon.`,
    });
    logger.info('Support ticket confirmation sent', { ticketId, to: userEmail });
  } catch (err) {
    logger.error('Failed to send support ticket confirmation', {
      ticketId,
      error: err instanceof Error ? err.message : String(err),
    });
  }

  // ── 2. Notification to support inbox ────────────────────────────────────
  try {
    await transporter.sendMail({
      from: `"CahooTravel Support" <${supportInbox}>`,
      to: supportInbox,
      replyTo: userEmail,
      subject: `[${ticketId}] ${esc(subject)}`,
      html: `
<!DOCTYPE html><html><head><meta charset="utf-8"/></head>
<body style="${sharedStyles}">
  <table align="center" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;margin:0 auto;">
    <tr><td style="${cardStyles}">
      <h2 style="color:#4C1D95;font-size:18px;margin:0 0 16px;">New support ticket</h2>
      <table width="100%" cellpadding="0" cellspacing="0" style="background:#f9fafb;border-radius:8px;padding:16px;margin-bottom:20px;">
        <tr><td style="color:#374151;font-size:13px;padding:4px 0;"><strong>Ticket ID:</strong> ${esc(ticketId)}</td></tr>
        <tr><td style="color:#374151;font-size:13px;padding:4px 0;"><strong>From:</strong> ${esc(userEmail)}</td></tr>
        <tr><td style="color:#374151;font-size:13px;padding:4px 0;"><strong>Category:</strong> ${esc(category)}</td></tr>
        <tr><td style="color:#374151;font-size:13px;padding:4px 0;"><strong>Subject:</strong> ${esc(subject)}</td></tr>
      </table>
      <p style="color:#374151;font-size:14px;line-height:1.7;white-space:pre-wrap;">${esc(message)}</p>
    </td></tr>
  </table>
</body></html>`.trim(),
      text: `New ticket ${ticketId} from ${userEmail}\nCategory: ${category}\nSubject: ${subject}\n\n${message}`,
    });
    logger.info('Support ticket notification sent to inbox', { ticketId, to: supportInbox });
  } catch (err) {
    logger.error('Failed to send support ticket notification', {
      ticketId,
      error: err instanceof Error ? err.message : String(err),
    });
  }
}
