import "server-only";
import nodemailer from "nodemailer";
import type { Locale } from "@/lib/i18n/config";
import { formatPrice } from "@/lib/money";
import { getSettings, setting } from "@/lib/settings";

type MailOrder = {
  reference: string;
  customerName: string;
  email: string;
  total: number;
  subtotal: number;
  shipping: number;
  discount: number;
  paymentMethod: string;
  city: string;
  country: string;
  items: { name: string; quantity: number; unitPrice: number; total: number; variantName: string | null }[];
};

const copy = {
  fr: {
    subject: (ref: string) => `Votre commande ${ref} — DAR ZELLIGE`,
    title: "Merci pour votre commande",
    intro: (name: string) => `Bonjour ${name},

Nous avons bien reçu votre commande et notre atelier la prépare avec soin.`,
    ref: "Référence",
    items: "Votre commande",
    subtotal: "Sous-total",
    shipping: "Livraison",
    discount: "Remise",
    total: "Total",
    payment: "Mode de paiement",
    delivery: "Livraison",
    outro: "Notre équipe vous contactera pour confirmer la livraison. Pour toute question, répondez simplement à cet e-mail.",
    sign: "L'équipe DAR ZELLIGE",
  },
  en: {
    subject: (ref: string) => `Your order ${ref} — DAR ZELLIGE`,
    title: "Thank you for your order",
    intro: (name: string) => `Hello ${name},

We have received your order and our atelier is preparing it with care.`,
    ref: "Reference",
    items: "Your order",
    subtotal: "Subtotal",
    shipping: "Shipping",
    discount: "Discount",
    total: "Total",
    payment: "Payment method",
    delivery: "Delivery",
    outro: "Our team will contact you to confirm delivery. For any question, simply reply to this email.",
    sign: "The DAR ZELLIGE team",
  },
  ar: {
    subject: (ref: string) => `طلبك ${ref} — دار الزليج`,
    title: "شكرًا لطلبك",
    intro: (name: string) => `مرحبًا ${name}،

استلمنا طلبك وورشنا تحضّره بعناية.`,
    ref: "المرجع",
    items: "طلبك",
    subtotal: "المجموع الفرعي",
    shipping: "التوصيل",
    discount: "الخصم",
    total: "المجموع",
    payment: "طريقة الدفع",
    delivery: "التوصيل",
    outro: "سيتواصل معك فريقنا لتأكيد التوصيل. لأي سؤال، ردّ على هذا البريد.",
    sign: "فريق دار الزليج",
  },
} as const;

const paymentLabels: Record<string, Record<string, string>> = {
  fr: { COD: "Paiement à la livraison", BANK_TRANSFER: "Virement bancaire", ONLINE: "Paiement en ligne" },
  en: { COD: "Cash on delivery", BANK_TRANSFER: "Bank transfer", ONLINE: "Online payment" },
  ar: { COD: "الدفع عند الاستلام", BANK_TRANSFER: "تحويل بنكي", ONLINE: "دفع إلكتروني" },
};

export function isEmailConfigured() {
  return Boolean(process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASSWORD);
}

async function transporter() {
  if (!isEmailConfigured()) return null;
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number.parseInt(process.env.SMTP_PORT ?? "587", 10),
    secure: process.env.SMTP_SECURE === "true",
    auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASSWORD },
  });
}

function escapeHtml(value: string) {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function layout(locale: Locale, body: string) {
  const dir = locale === "ar" ? "rtl" : "ltr";
  return `<!doctype html><html lang="${locale}" dir="${dir}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"></head>
  <body style="margin:0;background:#F7F3EB;font-family:Helvetica,Arial,sans-serif;color:#24221D;">
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#F7F3EB;padding:32px 16px;">
      <tr><td align="center">
        <table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;background:#FFFDF8;border:1px solid #E7DECD;">
          <tr><td style="padding:28px 32px;border-bottom:1px solid #E7DECD;text-align:center;">
            <div style="font-family:Georgia,serif;font-size:22px;letter-spacing:6px;color:#24221D;">DAR ZELLIGE</div>
            <div style="font-size:10px;letter-spacing:3px;color:#B99A64;margin-top:6px;">MARRAKECH · MOROCCO</div>
          </td></tr>
          <tr><td style="padding:32px;">${body}</td></tr>
          <tr><td style="padding:20px 32px;border-top:1px solid #E7DECD;font-size:11px;color:#7A746a;text-align:center;">
            DAR ZELLIGE — 12, Derb El Ferrane, Médina, Marrakech · hello@darzellige.ma<br>
            Démonstrateur de portfolio. Aucun paiement réel n'est traité.
          </td></tr>
        </table>
      </td></tr>
    </table>
  </body></html>`;
}

export async function sendOrderConfirmation(order: MailOrder, locale: Locale = "fr") {
  const settings = await getSettings();
  const t = copy[locale] ?? copy.fr;
  const brand = setting(settings, "brand.name") || "DAR ZELLIGE";
  const html = layout(
    locale,
    `<h1 style="font-family:Georgia,serif;font-weight:400;font-size:26px;margin:0 0 16px;">${t.title}</h1>
     <p style="font-size:14px;line-height:1.7;white-space:pre-line;color:#4A463e;">${escapeHtml(t.intro(order.customerName))}</p>
     <p style="font-size:12px;letter-spacing:1px;text-transform:uppercase;color:#7A746a;margin:24px 0 4px;">${t.ref}</p>
     <p style="font-family:Georgia,serif;font-size:20px;margin:0 0 24px;">${escapeHtml(order.reference)}</p>
     <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="font-size:13px;color:#4A463e;border-top:1px solid #E7DECD;">
       <tr><td colspan="2" style="padding:16px 0 8px;font-size:11px;letter-spacing:1px;text-transform:uppercase;color:#7A746a;">${t.items}</td></tr>
       ${order.items
         .map(
           (item) => `<tr>
             <td style="padding:8px 0;border-bottom:1px solid #F0EADF;">${escapeHtml(item.name)}${item.variantName ? ` — ${escapeHtml(item.variantName)}` : ""}<br><span style="color:#7A746a;font-size:12px;">× ${item.quantity}</span></td>
             <td align="right" style="padding:8px 0;border-bottom:1px solid #F0EADF;white-space:nowrap;">${formatPrice(item.total, locale)}</td>
           </tr>`,
         )
         .join("")}
       <tr><td style="padding:10px 0 2px;">${t.subtotal}</td><td align="right">${formatPrice(order.subtotal, locale)}</td></tr>
       <tr><td style="padding:2px 0;">${t.shipping}</td><td align="right">${order.shipping === 0 ? "—" : formatPrice(order.shipping, locale)}</td></tr>
       ${order.discount > 0 ? `<tr><td style="padding:2px 0;">${t.discount}</td><td align="right">−${formatPrice(order.discount, locale)}</td></tr>` : ""}
       <tr><td style="padding:12px 0 0;font-family:Georgia,serif;font-size:18px;">${t.total}</td><td align="right" style="padding:12px 0 0;font-family:Georgia,serif;font-size:18px;">${formatPrice(order.total, locale)}</td></tr>
     </table>
     <p style="font-size:13px;line-height:1.7;color:#4A463e;margin:24px 0 0;"><strong>${t.payment}:</strong> ${paymentLabels[locale]?.[order.paymentMethod] ?? order.paymentMethod}<br>
     <strong>${t.delivery}:</strong> ${escapeHtml(order.city)}, ${escapeHtml(order.country)}</p>
     <p style="font-size:13px;line-height:1.7;color:#4A463e;margin:24px 0 0;">${t.outro}</p>
     <p style="font-size:13px;color:#7A746a;margin:24px 0 0;">${t.sign}</p>`,
  );

  const transporterInstance = await transporter();
  if (!transporterInstance) {
    console.info(`[email] SMTP non configuré — confirmation de commande ${order.reference} non envoyée.`);
    return false;
  }

  try {
    await transporterInstance.sendMail({
      from: process.env.SMTP_FROM ?? process.env.EMAIL_FROM ?? `"${brand}" <hello@darzellige.ma>`,
      to: order.email,
      subject: t.subject(order.reference),
      html,
    });
    return true;
  } catch (error) {
    console.error("[email] Échec de l'envoi de la confirmation", error);
    return false;
  }
}

export async function sendContactNotification(input: {
  name: string;
  email: string;
  subject: string;
  message: string;
}) {
  const transporterInstance = await transporter();
  const settings = await getSettings();
  if (!transporterInstance) {
    console.info("[email] SMTP non configuré — message de contact non envoyé.");
    return false;
  }
  try {
    await transporterInstance.sendMail({
      from: process.env.SMTP_FROM ?? process.env.EMAIL_FROM ?? "hello@darzellige.ma",
      to: setting(settings, "contact.email") || "hello@darzellige.ma",
      replyTo: input.email,
      subject: `[Contact] ${input.subject}`,
      text: `De : ${input.name} <${input.email}>

${input.message}`,
    });
    return true;
  } catch (error) {
    console.error("[email] Échec de l'envoi du message de contact", error);
    return false;
  }
}