/**
 * Order Cancelled Email Template
 * 
 * Refactored to use the abstracted email service architecture.
 */

import Handlebars from "handlebars";
import { emailServiceConfig, DEFAULT_LANGUAGE } from "@/lib/email/config";

// Cancelled order specific translations
const cancelledTranslations = {
  en: {
    subject: "Order {{orderNumber}} Cancelled",
    title: "Order Cancelled",
    greeting: "Dear {{customerName}},",
    body: "Your order has been cancelled. If you have any questions, please contact us.",
    orderLabel: "Order:",
    dateLabel: "Date:",
    reasonLabel: "Reason:",
    noReason: "No reason provided",
    itemsLabel: "Items",
    contactButton: "Contact Us",
    thankYou: "Thank you!",
    companyName: emailServiceConfig.companyName,
    footerText: emailServiceConfig.fromEmail,
  },
  sr: {
    subject: "Porudžbina {{orderNumber}} Otkazana",
    title: "Porudžbina Otkazana",
    greeting: "Poštovani {{customerName}},",
    body: "Vaša porudžbina je otkazana. Ako imate pitanja, molimo vas da nas kontaktirate.",
    orderLabel: "Porudžbina:",
    dateLabel: "Datum:",
    reasonLabel: "Razlog:",
    noReason: "Razlog nije naveden",
    itemsLabel: "Artikli",
    contactButton: "Kontaktirajte Nas",
    thankYou: "Hvala vam!",
    companyName: emailServiceConfig.companyName,
    footerText: emailServiceConfig.fromEmail,
  },
  de: {
    subject: "Bestellung {{orderNumber}} Storniert",
    title: "Bestellung Storniert",
    greeting: "Sehr geehrte/r {{customerName}},",
    body: "Ihre Bestellung wurde storniert. Bei Fragen kontaktieren Sie uns bitte.",
    orderLabel: "Bestellung:",
    dateLabel: "Datum:",
    reasonLabel: "Grund:",
    noReason: "Kein Grund angegeben",
    itemsLabel: "Artikel",
    contactButton: "Kontaktieren Sie Uns",
    thankYou: "Vielen Dank!",
    companyName: emailServiceConfig.companyName,
    footerText: emailServiceConfig.fromEmail,
  },
  fr: {
    subject: "Commande {{orderNumber}} Annulée",
    title: "Commande Annulée",
    greeting: "Cher/Chère {{customerName}},",
    body: "Votre commande a été annulée. Si vous avez des questions, veuillez nous contacter.",
    orderLabel: "Commande:",
    dateLabel: "Date:",
    reasonLabel: "Raison:",
    noReason: "Aucune raison fournie",
    itemsLabel: "Articles",
    contactButton: "Contactez-Nous",
    thankYou: "Merci!",
    companyName: emailServiceConfig.companyName,
    footerText: emailServiceConfig.fromEmail,
  },
};

// Template
const cancelledEmailTemplate = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body style="font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;background:#f6f6f6;margin:0;padding:20px;">
  <div style="max-width:600px;margin:0 auto;background:white;padding:40px 20px;">
    <div style="text-align:center;margin-bottom:30px;">
      <img src="{{companyLogoUrl}}" width="150" alt="{{companyName}}">
    </div>
    
    <h1 style="font-size:24px;font-weight:bold;color:#1a1a1a;margin-bottom:20px;">{{title}}</h1>
    
    <p style="font-size:16px;color:#333;margin-bottom:10px;">{{greeting}}</p>
    <p style="font-size:14px;color:#666;margin-bottom:20px;">{{body}}</p>
    
    <div style="background:#f9f9f9;padding:15px;border-radius:8px;margin-bottom:20px;">
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>{{orderLabel}}</strong> {{orderNumber}}</p>
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>{{dateLabel}}</strong> {{orderDate}}</p>
      <p style="font-size:14px;color:#333;margin:0;"><strong>{{reasonLabel}}</strong> {{cancellationReason}}</p>
    </div>
    
    <p style="font-size:16px;font-weight:bold;color:#1a1a1a;margin-bottom:10px;">{{itemsLabel}}</p>
    <div style="margin-bottom:20px;">
      {{#each items}}
      <p style="font-size:14px;color:#333;margin:0 0 4px 0;">{{quantity}}x {{name}} - {{price}}</p>
      {{/each}}
    </div>
    
    <div style="text-align:center;margin:20px 0;">
      <a href="{{storefrontUrl}}" style="display:inline-block;background:#000;color:white;padding:12px 30px;border-radius:4px;text-decoration:none;font-size:14px;font-weight:bold;">{{contactButton}}</a>
    </div>
    
    <p style="font-size:14px;color:#666;margin-bottom:10px;">{{footerText}}</p>
    <p style="font-size:14px;font-weight:bold;color:#1a1a1a;">{{thankYou}}</p>
    
    <div style="margin-top:40px;padding-top:20px;border-top:1px solid #e0e0e0;text-align:center;color:#666;font-size:12px;">
      <p>{{companyName}}</p>
    </div>
  </div>
</body>
</html>
`;

const compileCancelledEmail = Handlebars.compile(cancelledEmailTemplate);

export function getOrderCancelledEmails(order: any) {
  const lang = (order.languageCode?.toLowerCase() || DEFAULT_LANGUAGE) as keyof typeof cancelledTranslations;
  const t = cancelledTranslations[lang] || cancelledTranslations[DEFAULT_LANGUAGE];
  
  const customerName = order.shippingAddress?.firstName 
    ? `${order.shippingAddress.firstName} ${order.shippingAddress.lastName || ""}`.trim()
    : order.userEmail?.split("@")[0] || "Customer";
    
  const currency = order.total?.gross?.currency || "EUR";
  const orderDate = order.created 
    ? new Date(order.created).toLocaleString(lang === "sr" ? "sr-RS" : lang === "de" ? "de-DE" : lang === "fr" ? "fr-FR" : "en-US")
    : new Date().toLocaleString();
  const cancellationReason = order.metadata?.find((m: { key: string; value: string }) => m.key === "cancellation_reason")?.value || t.noReason;

  const greeting = Handlebars.compile(t.greeting)({ customerName });
  const subject = Handlebars.compile(t.subject)({ orderNumber: order.number || order.id });

  const items = (order.lines || []).map((line: any) => ({
    name: line.variant?.product?.name || line.variant?.name || "Product",
    quantity: line.quantity || 0,
    price: `${line.totalPrice?.gross?.amount?.toFixed(2) || "0.00"} ${currency}`
  }));

  const emailData = {
    ...t,
    greeting,
    orderNumber: order.number || order.id,
    orderDate,
    cancellationReason,
    items,
    companyLogoUrl: emailServiceConfig.companyLogoUrl,
    storefrontUrl: emailServiceConfig.storefrontUrl,
  };

  return {
    customerSubject: subject,
    customerHtml: compileCancelledEmail(emailData),
    adminSubject: `Order Cancelled #${order.number || order.id}`,
    adminHtml: compileCancelledEmail({
      ...emailData,
      title: `Order Cancelled - #${order.number || order.id}`,
      body: `Order has been cancelled. Customer: ${order.userEmail}. Reason: ${cancellationReason}`,
    }),
  };
}
