import nodemailer from 'nodemailer'

interface EmailData {
  name: string
  email: string
  message: string
}

interface SubscriptionData {
  name: string
  email: string
}

export async function sendEmail(data: EmailData) {
  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT),
    secure: process.env.SMTP_SECURE === 'true',
    auth: {
      user: process.env.GOOGLE_EMAIL,
      pass: process.env.GOOGLE_APP_PASSWORD,
    },
  })

  const mailOptions = {
    from: process.env.GOOGLE_EMAIL,
    to: process.env.RECIPIENT_EMAIL,
    subject: 'New Contact Form Submission',
    html: `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
        <h2 style="color: #2563eb;">New Contact Form Submission</h2>
        <div style="background-color: #f3f4f6; padding: 20px; border-radius: 8px;">
          <p><strong>Name:</strong> ${data.name}</p>
          <p><strong>Email:</strong> ${data.email}</p>
          <p><strong>Message:</strong></p>
          <p style="white-space: pre-wrap;">${data.message}</p>
        </div>
      </div>
    `,
  }

  const info = await transporter.sendMail(mailOptions)
  return info
}

export async function sendSubscriptionEmail(data: SubscriptionData) {
  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT),
    secure: process.env.SMTP_SECURE === 'true',
    auth: {
      user: process.env.GOOGLE_EMAIL,
      pass: process.env.GOOGLE_APP_PASSWORD,
    },
  })

  const now = new Date()
  const timestamp = now.toLocaleString('en-US', {
    timeZone: 'America/Chicago',
    dateStyle: 'full',
    timeStyle: 'long'
  })

  const mailOptions = {
    from: process.env.GOOGLE_EMAIL,
    to: process.env.RECIPIENT_EMAIL,
    subject: 'New Video Notification Subscription',
    html: `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
        <h2 style="color: #2563eb;">New Video Notification Subscription</h2>
        <div style="background-color: #f3f4f6; padding: 20px; border-radius: 8px;">
          <p><strong>Subscriber Name:</strong> ${data.name}</p>
          <p><strong>Email Address:</strong> ${data.email}</p>
          <p><strong>Subscription Date:</strong> ${timestamp}</p>
          <p><strong>Source:</strong> Resources Page Video Notifications</p>
        </div>
        <p style="margin-top: 20px; color: #6b7280;">This user would like to be notified when new training videos are added to the Resources page.</p>
      </div>
    `,
  }

  const info = await transporter.sendMail(mailOptions)
  return info
}
