import nodemailer from 'nodemailer'
import type { Order } from '@prisma/client'

function createTransport() {
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT ?? 587),
    secure: process.env.SMTP_SECURE === 'true',
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  })
}

const PRODUCT_NAMES: Record<string, string> = {
  samarreta: 'Samarreta Cursa de la Cirera 2026',
  mitjons: 'Mitjons Cursa de la Cirera 2026',
  pack: 'Pack Samarreta + Mitjons Cursa de la Cirera 2026',
}

const STATUS_LABELS: Record<string, string> = {
  PENDING: 'Pendent',
  PAID: 'Pagat',
  PREPARING: 'En preparació',
  SHIPPED: 'Enviat',
  DELIVERED: 'Lliurat',
  CANCELLED: 'Cancel·lat',
}

function formatSizes(order: Order): string {
  const parts: string[] = []
  if (order.sizeTshirt) parts.push(`Samarreta: ${order.sizeTshirt}`)
  if (order.sizeSocks) parts.push(`Mitjons: ${order.sizeSocks}`)
  return parts.join(' · ') || '—'
}

function formatShipping(order: Order): string {
  if (order.shipping === 'correos') {
    return `Correos Express (+${order.shippingAmount.toFixed(2).replace('.', ',')}€)`
  }
  return 'Recollida a Corbins/Lleida (gratuït)'
}

function baseEmailHtml(content: string): string {
  return `<!DOCTYPE html>
<html lang="ca">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
  body { margin: 0; padding: 0; background: #070714; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
  .container { max-width: 600px; margin: 0 auto; background: #0E0E1F; }
  .header { background: linear-gradient(135deg, #0E0E1F 0%, #1C1C38 100%); padding: 32px 40px; text-align: center; border-bottom: 2px solid #00C8DC; }
  .header h1 { color: #00C8DC; font-size: 14px; letter-spacing: 3px; text-transform: uppercase; margin: 0 0 4px; }
  .header h2 { color: #FFFFFF; font-size: 22px; font-weight: 800; margin: 0; }
  .body { padding: 32px 40px; }
  .order-box { background: #1C1C38; border-radius: 12px; padding: 24px; margin: 20px 0; }
  .order-number { color: #00C8DC; font-size: 24px; font-weight: 800; letter-spacing: 2px; }
  .row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #2A2A45; }
  .row:last-child { border-bottom: none; }
  .row .label { color: #8888AA; font-size: 14px; }
  .row .value { color: #FFFFFF; font-size: 14px; font-weight: 600; }
  .total-row { display: flex; justify-content: space-between; padding: 16px 0 0; margin-top: 8px; }
  .total-row .label { color: #FFFFFF; font-size: 16px; font-weight: 700; }
  .total-row .value { color: #00C8DC; font-size: 20px; font-weight: 800; }
  .info-box { background: #1C1C38; border-left: 3px solid #00C8DC; border-radius: 0 8px 8px 0; padding: 16px 20px; margin: 20px 0; }
  .info-box p { color: #CCCCDD; font-size: 14px; margin: 0 0 8px; }
  .info-box p:last-child { margin: 0; }
  .footer { background: #070714; padding: 24px 40px; text-align: center; border-top: 1px solid #1C1C38; }
  .footer p { color: #555577; font-size: 12px; margin: 4px 0; }
  h3 { color: #FFFFFF; font-size: 16px; margin: 24px 0 12px; }
  .address { color: #CCCCDD; font-size: 14px; line-height: 1.6; }
</style>
</head>
<body>
<div class="container">
${content}
<div class="footer">
  <p>Blood Bros Sport · Cursa de la Cirera 2026 · Corbins, Lleida</p>
  <p>Patrocinador principal: Finques Prats</p>
</div>
</div>
</body>
</html>`
}

export async function sendOrderConfirmationToClient(order: Order) {
  if (!process.env.SMTP_HOST) return

  const transporter = createTransport()
  const productName = PRODUCT_NAMES[order.product] ?? order.product
  const sizes = formatSizes(order)
  const shippingText = formatShipping(order)

  const addressBlock =
    order.shipping === 'correos'
      ? `<div class="info-box"><p><strong>Adreça d'enviament:</strong></p><p class="address">${order.nom} ${order.cognoms}<br>${order.adreca}<br>${order.codiPostal} ${order.poblacio} (${order.provincia})</p></div>`
      : `<div class="info-box"><p><strong>Punt de recollida:</strong> Corbins / Lleida</p><p>Ens posarem en contacte amb tu per coordinar l'entrega.</p></div>`

  const html = baseEmailHtml(`
<div class="header">
  <h1>Blood Bros Sport</h1>
  <h2>Confirmació de comanda</h2>
</div>
<div class="body">
  <p style="color:#CCCCDD; font-size:16px; margin:0 0 8px;">Hola ${order.nom},</p>
  <p style="color:#8888AA; font-size:14px; margin:0 0 24px;">Hem rebut la teva comanda. Aquí tens el resum:</p>

  <div class="order-box">
    <div style="text-align:center; margin-bottom:16px;">
      <div style="color:#8888AA; font-size:12px; letter-spacing:2px; text-transform:uppercase;">Número de comanda</div>
      <div class="order-number">${order.orderNumber}</div>
    </div>
    <div class="row"><span class="label">Producte</span><span class="value">${productName}</span></div>
    <div class="row"><span class="label">Talles</span><span class="value">${sizes}</span></div>
    <div class="row"><span class="label">Lliurament</span><span class="value">${shippingText}</span></div>
    <div class="row"><span class="label">Producte</span><span class="value">${order.baseAmount.toFixed(2).replace('.', ',')}€</span></div>
    ${order.shippingAmount > 0 ? `<div class="row"><span class="label">Enviament</span><span class="value">${order.shippingAmount.toFixed(2).replace('.', ',')}€</span></div>` : ''}
    <div class="total-row"><span class="label">Total pagat</span><span class="value">${order.totalAmount.toFixed(2).replace('.', ',')}€</span></div>
  </div>

  ${addressBlock}

  <div class="info-box" style="border-color:#E84040;">
    <p><strong style="color:#E84040;">Calendari de lliurament</strong></p>
    <p>Periode de comandes: 18 – 25 de Juny 2026</p>
    <p>Lliurament previst: 29 de Juny – 3 de Juliol 2026</p>
  </div>

  <h3>Necessites ajuda?</h3>
  <p style="color:#8888AA; font-size:14px;">Si tens qualsevol dubte sobre la teva comanda ${order.orderNumber}, contacta'ns. Estem aquí per ajudar-te.</p>
  <p style="color:#8888AA; font-size:14px; margin-top:24px;">Moltes gràcies per la teva confiança!<br><strong style="color:#FFFFFF;">L'equip de Blood Bros Sport</strong></p>
</div>`)

  await transporter.sendMail({
    from: `"Blood Bros Sport" <${process.env.SMTP_FROM ?? process.env.SMTP_USER}>`,
    to: order.email,
    subject: `Confirmació comanda ${order.orderNumber} – Cursa de la Cirera 2026`,
    html,
  })
}

export async function sendNewOrderNotificationToAdmin(order: Order) {
  if (!process.env.SMTP_HOST || !process.env.ADMIN_EMAIL) return

  const transporter = createTransport()
  const productName = PRODUCT_NAMES[order.product] ?? order.product
  const sizes = formatSizes(order)
  const shippingText = formatShipping(order)

  const addressBlock =
    order.shipping === 'correos'
      ? `<div class="row"><span class="label">Adreça</span><span class="value" style="text-align:right;">${order.adreca}<br>${order.codiPostal} ${order.poblacio}<br>${order.provincia}</span></div>`
      : `<div class="row"><span class="label">Recollida a</span><span class="value">Corbins / Lleida</span></div>`

  const html = baseEmailHtml(`
<div class="header">
  <h1>Nova comanda rebuda</h1>
  <h2>${order.orderNumber}</h2>
</div>
<div class="body">
  <div class="order-box">
    <div class="row"><span class="label">Producte</span><span class="value">${productName}</span></div>
    <div class="row"><span class="label">Talles</span><span class="value">${sizes}</span></div>
    <div class="row"><span class="label">Lliurament</span><span class="value">${shippingText}</span></div>
    <div class="total-row"><span class="label">TOTAL</span><span class="value">${order.totalAmount.toFixed(2).replace('.', ',')}€</span></div>
  </div>

  <h3>Dades del client</h3>
  <div class="order-box">
    <div class="row"><span class="label">Nom</span><span class="value">${order.nom} ${order.cognoms}</span></div>
    <div class="row"><span class="label">Telèfon</span><span class="value">${order.telefon}</span></div>
    <div class="row"><span class="label">Email</span><span class="value">${order.email}</span></div>
    ${addressBlock}
  </div>

  <div style="text-align:center; margin-top:24px;">
    <a href="${process.env.NEXT_PUBLIC_BASE_URL}/admin" style="display:inline-block; background:#00C8DC; color:#000; padding:12px 32px; border-radius:8px; text-decoration:none; font-weight:700; font-size:14px; letter-spacing:1px; text-transform:uppercase;">Veure al panel d'admin</a>
  </div>
</div>`)

  await transporter.sendMail({
    from: `"Blood Bros Sport" <${process.env.SMTP_FROM ?? process.env.SMTP_USER}>`,
    to: process.env.ADMIN_EMAIL,
    subject: `[NOVA COMANDA] ${order.orderNumber} – ${productName} – ${order.nom} ${order.cognoms}`,
    html,
  })
}

export async function sendStatusUpdateToClient(order: Order) {
  if (!process.env.SMTP_HOST) return

  const transporter = createTransport()
  const statusLabel = STATUS_LABELS[order.status] ?? order.status

  const html = baseEmailHtml(`
<div class="header">
  <h1>Actualització de comanda</h1>
  <h2>${order.orderNumber}</h2>
</div>
<div class="body">
  <p style="color:#CCCCDD; font-size:16px; margin:0 0 8px;">Hola ${order.nom},</p>
  <p style="color:#8888AA; font-size:14px; margin:0 0 24px;">Hi ha una actualització en la teva comanda:</p>

  <div class="order-box" style="text-align:center;">
    <div style="color:#8888AA; font-size:12px; letter-spacing:2px; text-transform:uppercase; margin-bottom:8px;">Estat actual</div>
    <div style="color:#00C8DC; font-size:28px; font-weight:800;">${statusLabel.toUpperCase()}</div>
    <div style="color:#8888AA; font-size:14px; margin-top:4px;">Comanda ${order.orderNumber}</div>
  </div>

  <div class="info-box">
    <p>Qualsevol dubte, contacta'ns i et responem de seguida.</p>
    <p><strong style="color:#FFFFFF;">L'equip de Blood Bros Sport</strong></p>
  </div>
</div>`)

  await transporter.sendMail({
    from: `"Blood Bros Sport" <${process.env.SMTP_FROM ?? process.env.SMTP_USER}>`,
    to: order.email,
    subject: `Actualització comanda ${order.orderNumber} – ${statusLabel}`,
    html,
  })
}
