import nodemailer from 'nodemailer'

const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: Number(process.env.SMTP_PORT) || 587,
  secure: false,
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASS,
  },
})

const FROM = process.env.SMTP_FROM || 'AmaneNime Store <noreply@amanenime.my.id>'
const APP_NAME = process.env.APP_NAME || 'AmaneNime Store'
const APP_URL = process.env.APP_URL || 'https://store.amanenime.my.id'

// ============================================
// EMAIL TEMPLATES
// ============================================

function baseTemplate(content: string): string {
  return `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>${APP_NAME}</title>
    </head>
    <body style="font-family: 'Segoe UI', Arial, sans-serif; background: #0a0a0f; margin: 0; padding: 20px;">
      <div style="max-width: 600px; margin: 0 auto; background: #1a1a2e; border-radius: 16px; overflow: hidden; border: 1px solid rgba(245,158,11,0.2);">
        <!-- Header -->
        <div style="background: linear-gradient(135deg, #f59e0b, #d97706); padding: 30px; text-align: center;">
          <h1 style="color: #000; margin: 0; font-size: 24px; font-weight: 800; letter-spacing: 1px;">
            ⚡ ${APP_NAME}
          </h1>
          <p style="color: rgba(0,0,0,0.7); margin: 5px 0 0;">Top Up Game & Digital Products</p>
        </div>
        <!-- Content -->
        <div style="padding: 30px; color: #e2e8f0;">
          ${content}
        </div>
        <!-- Footer -->
        <div style="background: rgba(0,0,0,0.3); padding: 20px; text-align: center; border-top: 1px solid rgba(245,158,11,0.1);">
          <p style="color: #64748b; margin: 0; font-size: 12px;">
            © 2026 ${APP_NAME}. All rights reserved.<br>
            <a href="${APP_URL}" style="color: #f59e0b; text-decoration: none;">${APP_URL}</a>
          </p>
        </div>
      </div>
    </body>
    </html>
  `
}

// ============================================
// ORDER SUCCESS EMAIL
// ============================================

export async function sendOrderSuccessEmail(to: string, data: {
  name: string
  orderId: string
  productName: string
  targetId?: string
  zone?: string
  price: number
}) {
  const content = `
    <h2 style="color: #f59e0b; margin-top: 0;">✅ Pesanan Berhasil!</h2>
    <p>Hai <strong>${data.name}</strong>,</p>
    <p>Pesanan kamu telah berhasil diproses!</p>
    <div style="background: rgba(245,158,11,0.1); border: 1px solid rgba(245,158,11,0.3); border-radius: 12px; padding: 20px; margin: 20px 0;">
      <table style="width: 100%; border-collapse: collapse;">
        <tr><td style="color: #94a3b8; padding: 6px 0;">Order ID</td><td style="color: #e2e8f0; font-weight: 600;">#${data.orderId.toUpperCase()}</td></tr>
        <tr><td style="color: #94a3b8; padding: 6px 0;">Produk</td><td style="color: #e2e8f0;">${data.productName}</td></tr>
        ${data.targetId ? `<tr><td style="color: #94a3b8; padding: 6px 0;">ID Tujuan</td><td style="color: #e2e8f0;">${data.targetId}${data.zone ? ` (${data.zone})` : ''}</td></tr>` : ''}
        <tr><td style="color: #94a3b8; padding: 6px 0;">Total</td><td style="color: #f59e0b; font-weight: 700;">Rp ${data.price.toLocaleString('id-ID')}</td></tr>
      </table>
    </div>
    <a href="${APP_URL}/dashboard/orders" style="display: inline-block; background: linear-gradient(135deg, #f59e0b, #d97706); color: #000; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 700; margin-top: 10px;">
      Lihat Detail Order →
    </a>
  `
  await transporter.sendMail({
    from: FROM,
    to,
    subject: `✅ Order Berhasil - ${data.productName} | ${APP_NAME}`,
    html: baseTemplate(content),
  })
}

// ============================================
// ACCOUNT DELIVERY EMAIL
// ============================================

export async function sendAccountDeliveryEmail(to: string, data: {
  name: string
  orderId: string
  productName: string
  email: string
  password: string
  extra?: string
}) {
  const content = `
    <h2 style="color: #f59e0b; margin-top: 0;">📦 Akun Premium Kamu Sudah Siap!</h2>
    <p>Hai <strong>${data.name}</strong>,</p>
    <p>Terima kasih sudah berbelanja di ${APP_NAME}. Berikut detail akun premium kamu:</p>
    <div style="background: rgba(245,158,11,0.1); border: 1px solid rgba(245,158,11,0.3); border-radius: 12px; padding: 20px; margin: 20px 0;">
      <h3 style="color: #f59e0b; margin-top: 0;">🔐 ${data.productName}</h3>
      <table style="width: 100%; border-collapse: collapse;">
        <tr>
          <td style="color: #94a3b8; padding: 8px 0; width: 100px;">Email</td>
          <td style="color: #e2e8f0; font-family: monospace; background: rgba(0,0,0,0.3); padding: 6px 10px; border-radius: 6px; font-weight: 600;">${data.email}</td>
        </tr>
        <tr>
          <td style="color: #94a3b8; padding: 8px 0;">Password</td>
          <td style="color: #e2e8f0; font-family: monospace; background: rgba(0,0,0,0.3); padding: 6px 10px; border-radius: 6px; font-weight: 600;">${data.password}</td>
        </tr>
        ${data.extra ? `<tr><td style="color: #94a3b8; padding: 8px 0;">Info</td><td style="color: #e2e8f0;">${data.extra}</td></tr>` : ''}
      </table>
    </div>
    <p style="color: #f87171; font-size: 13px;">⚠️ Jangan share akun ini kepada siapapun. Segera ganti password setelah login.</p>
    <a href="${APP_URL}/dashboard/orders" style="display: inline-block; background: linear-gradient(135deg, #f59e0b, #d97706); color: #000; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 700; margin-top: 10px;">
      Lihat Produk Saya →
    </a>
  `
  await transporter.sendMail({
    from: FROM,
    to,
    subject: `📦 Akun ${data.productName} Siap Digunakan | ${APP_NAME}`,
    html: baseTemplate(content),
  })
}

// ============================================
// PASSWORD RESET EMAIL
// ============================================

export async function sendPasswordResetEmail(to: string, data: {
  name: string
  resetUrl: string
}) {
  const content = `
    <h2 style="color: #f59e0b; margin-top: 0;">🔑 Reset Password</h2>
    <p>Hai <strong>${data.name}</strong>,</p>
    <p>Kamu meminta reset password untuk akun ${APP_NAME}. Klik tombol di bawah untuk melanjutkan:</p>
    <a href="${data.resetUrl}" style="display: inline-block; background: linear-gradient(135deg, #f59e0b, #d97706); color: #000; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 700; margin: 20px 0;">
      Reset Password →
    </a>
    <p style="color: #64748b; font-size: 13px;">Link ini akan expired dalam <strong>1 jam</strong>. Jika kamu tidak meminta reset password, abaikan email ini.</p>
  `
  await transporter.sendMail({
    from: FROM,
    to,
    subject: `🔑 Reset Password | ${APP_NAME}`,
    html: baseTemplate(content),
  })
}

// ============================================
// PAYMENT SUCCESS EMAIL
// ============================================

export async function sendPaymentSuccessEmail(to: string, data: {
  name: string
  amount: number
  type: 'wallet' | 'order'
  description: string
}) {
  const content = `
    <h2 style="color: #f59e0b; margin-top: 0;">💰 Pembayaran Berhasil!</h2>
    <p>Hai <strong>${data.name}</strong>,</p>
    <p>Pembayaran kamu telah berhasil dikonfirmasi.</p>
    <div style="background: rgba(245,158,11,0.1); border: 1px solid rgba(245,158,11,0.3); border-radius: 12px; padding: 20px; margin: 20px 0; text-align: center;">
      <p style="color: #94a3b8; margin: 0 0 8px;">Total Pembayaran</p>
      <p style="color: #f59e0b; font-size: 32px; font-weight: 800; margin: 0;">Rp ${data.amount.toLocaleString('id-ID')}</p>
      <p style="color: #94a3b8; margin: 8px 0 0; font-size: 14px;">${data.description}</p>
    </div>
    <a href="${APP_URL}/dashboard" style="display: inline-block; background: linear-gradient(135deg, #f59e0b, #d97706); color: #000; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 700;">
      Buka Dashboard →
    </a>
  `
  await transporter.sendMail({
    from: FROM,
    to,
    subject: `💰 Pembayaran Berhasil - Rp ${data.amount.toLocaleString('id-ID')} | ${APP_NAME}`,
    html: baseTemplate(content),
  })
}
