import nodemailer from 'nodemailer'

interface OrderData {
  phone: string
  productName: string
  productSlug: string
  timestamp: string
}

export async function sendEmail(data: OrderData): Promise<void> {
  const {
    SMTP_HOST,
    SMTP_PORT,
    SMTP_USER,
    SMTP_PASS,
    NOTIFICATION_EMAIL,
  } = process.env

  // Debug: Log SMTP configuration status
  console.log('SMTP Config Debug:', {
    SMTP_HOST: !!SMTP_HOST,
    SMTP_PORT: !!SMTP_PORT,
    NOTIFICATION_EMAIL: !!NOTIFICATION_EMAIL,
    SMTP_USER: !!SMTP_USER,
    SMTP_PASS: !!SMTP_PASS,
  })

  if (!SMTP_HOST || !SMTP_PORT || !NOTIFICATION_EMAIL) {
    const missing = []
    if (!SMTP_HOST) missing.push('SMTP_HOST')
    if (!SMTP_PORT) missing.push('SMTP_PORT')
    if (!NOTIFICATION_EMAIL) missing.push('NOTIFICATION_EMAIL')
    throw new Error(`SMTP configuration is missing: ${missing.join(', ')} are required`)
  }

  const smtpPort = parseInt(SMTP_PORT, 10)
  const isLocalhost = SMTP_HOST === 'localhost' || SMTP_HOST === '127.0.0.1'
  const requiresAuth = !isLocalhost || smtpPort !== 25

  if (requiresAuth && (!SMTP_USER || !SMTP_PASS)) {
    throw new Error('SMTP authentication is required for non-local SMTP servers')
  }

  // Configure transporter based on SMTP settings
  const isSecure = smtpPort === 465

  // For local SMTP servers (localhost/port 25), authentication might not be required
  const auth = (!isLocalhost || smtpPort !== 25) && SMTP_USER && SMTP_PASS ? {
    user: SMTP_USER,
    pass: SMTP_PASS,
  } : undefined

  const transporter = nodemailer.createTransport({
    host: SMTP_HOST,
    port: smtpPort,
    secure: isSecure,
    // Only require TLS for non-local connections
    requireTLS: !isLocalhost,
    auth: auth,
  })

  const mailOptions = {
    from: SMTP_USER ? `"Modul Construction - МОДУЛЬНІ СПОРУДИ" <${SMTP_USER}>` : `"Modul Construction - МОДУЛЬНІ СПОРУДИ" <noreply@localhost>`,
    to: NOTIFICATION_EMAIL,
    subject: `Нова заявка: ${data.productName}`,
    html: `
      <!DOCTYPE html>
      <html>
        <head>
          <meta charset="utf-8">
          <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background-color: #0284c7; color: white; padding: 20px; text-align: center; }
            .content { background-color: #f9fafb; padding: 20px; }
            .info-box { background-color: white; padding: 15px; margin: 10px 0; border-left: 4px solid #0284c7; }
            .label { font-weight: bold; color: #0284c7; }
            .footer { text-align: center; padding: 20px; color: #666; font-size: 12px; }
          </style>
        </head>
        <body>
          <div class="container">
            <div class="header">
              <h1>Нова заявка на товар</h1>
            </div>
            <div class="content">
              <div class="info-box">
                <p><span class="label">Товар:</span> ${data.productName}</p>
              </div>
              <div class="info-box">
                <p><span class="label">Номер телефону:</span> <a href="tel:${data.phone}">${data.phone}</a></p>
              </div>
              <div class="info-box">
                <p><span class="label">Час заявки:</span> ${data.timestamp}</p>
              </div>
              <div class="info-box">
                <p><span class="label">Посилання на товар:</span> <a href="${process.env.NEXT_PUBLIC_SITE_URL || 'https://modul-construction.com.ua'}/products/${data.productSlug}/">Переглянути товар</a></p>
              </div>
            </div>
            <div class="footer">
              <p>Це автоматичне повідомлення з сайту Modul Construction - МОДУЛЬНІ СПОРУДИ</p>
            </div>
          </div>
        </body>
      </html>
    `,
    text: `
Нова заявка на товар

Товар: ${data.productName}
Номер телефону: ${data.phone}
Час заявки: ${data.timestamp}
Посилання на товар: ${process.env.NEXT_PUBLIC_SITE_URL || 'https://modul-construction.com.ua'}/products/${data.productSlug}/
    `,
  }

  await transporter.sendMail(mailOptions)
}

