import Handlebars from "handlebars";

// Translations for Order Shipped emails
const translations = {
  en: {
    subject: "Order {{orderNumber}} Has Shipped!",
    title: "Your Order Has Shipped!",
    greeting: "Dear {{customerName}},",
    body: "Great news! Your order has been shipped and is on its way.",
    orderLabel: "Order:",
    dateLabel: "Date:",
    trackingLabel: "Tracking Number:",
    itemsLabel: "Items",
    trackButton: "Track Your Order",
    thankYou: "Thank you!",
    companyName: "ManoonOils",
    footerText: "support@manoonoils.com"
  },
  sr: {
    subject: "Porudžbina {{orderNumber}} Poslata!",
    title: "Vaša Porudžbina je Poslata!",
    greeting: "Poštovani {{customerName}},",
    body: "Odlične vesti! Vaša porudžbina je poslata i na putu je.",
    orderLabel: "Porudžbina:",
    dateLabel: "Datum:",
    trackingLabel: "Broj Za Praćenje:",
    itemsLabel: "Artikli",
    trackButton: "Pratite Porudžbinu",
    thankYou: "Hvala vam!",
    companyName: "ManoonOils",
    footerText: "support@manoonoils.com"
  },
  de: {
    subject: "Bestellung {{orderNumber}} Wurde Versendet!",
    title: "Ihre Bestellung Wurde Versendet!",
    greeting: "Sehr geehrte/r {{customerName}},",
    body: "Tolle Neuigkeiten! Ihre Bestellung wurde versendet und ist unterwegs.",
    orderLabel: "Bestellung:",
    dateLabel: "Datum:",
    trackingLabel: "Sendungsnummer:",
    itemsLabel: "Artikel",
    trackButton: "Bestellung Verfolgen",
    thankYou: "Vielen Dank!",
    companyName: "ManoonOils",
    footerText: "support@manoonoils.com"
  },
  fr: {
    subject: "Commande {{orderNumber}} Expédiée!",
    title: "Votre Commande a été Expédiée!",
    greeting: "Cher/Chère {{customerName}},",
    body: "Bonne nouvelle! Votre commande a été expédiée et est en route.",
    orderLabel: "Commande:",
    dateLabel: "Date:",
    trackingLabel: "Numéro de Suivi:",
    itemsLabel: "Articles",
    trackButton: "Suivre la Commande",
    thankYou: "Merci!",
    companyName: "ManoonOils",
    footerText: "support@manoonoils.com"
  }
};

// Customer email template
const customerEmailTemplate = `
<!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="https://minio-api.nodecrew.me/manoon-media/2024/09/cropped-manoon-logo_256x-1-1.png" 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>
      {{#if trackingNumber}}
      <p style="font-size:14px;color:#333;margin:0;"><strong>{{trackingLabel}}</strong> {{trackingNumber}}</p>
      {{/if}}
    </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>
    
    {{#if trackingUrl}}
    <div style="text-align:center;margin:20px 0;">
      <a href="{{trackingUrl}}" style="display:inline-block;background:#000;color:white;padding:12px 30px;border-radius:4px;text-decoration:none;font-size:14px;font-weight:bold;">{{trackButton}}</a>
    </div>
    {{/if}}
    
    <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>
`;

// Admin email template
const adminEmailTemplate = `
<!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;">
    <h1 style="font-size:24px;font-weight:bold;color:#1a1a1a;margin-bottom:20px;">Order Shipped</h1>
    
    <div style="background:#f9f9f9;padding:15px;border-radius:8px;margin-bottom:20px;">
      <h3 style="font-size:16px;font-weight:bold;color:#1a1a1a;margin:0 0 10px 0;">Order #{{orderNumber}}</h3>
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>Date:</strong> {{orderDate}}</p>
      {{#if trackingNumber}}
      <p style="font-size:14px;color:#333;margin:0;"><strong>Tracking:</strong> {{trackingNumber}}</p>
      {{/if}}
    </div>
    
    <div style="background:#f9f9f9;padding:15px;border-radius:8px;margin-bottom:20px;">
      <h3 style="font-size:16px;font-weight:bold;color:#1a1a1a;margin:0 0 10px 0;">Customer</h3>
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>Name:</strong> {{customerName}}</p>
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>Email:</strong> {{customerEmail}}</p>
      <p style="font-size:14px;color:#333;margin:0;"><strong>Phone:</strong> {{#if phone}}{{phone}}{{else}}Not provided{{/if}}</p>
    </div>
    
    <p style="font-size:16px;font-weight:bold;color:#1a1a1a;margin-bottom:10px;">Items</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="https://dashboard.manoonoils.com/orders" style="display:inline-block;background:#000;color:white;padding:12px 30px;border-radius:4px;text-decoration:none;font-size:14px;font-weight:bold;">Dashboard</a>
    </div>
  </div>
</body>
</html>
`;

// Compile templates
const compileCustomerEmail = Handlebars.compile(customerEmailTemplate);
const compileAdminEmail = Handlebars.compile(adminEmailTemplate);

export function getOrderShippedEmails(order: any, fulfillment?: any) {
  // Detect language
  const lang = order.languageCode?.toLowerCase() || "en";
  const t = translations[lang as keyof typeof translations] || translations.en;
  
  // Format data
  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 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 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();
    
  // Get tracking info from fulfillment
  const trackingNumber = fulfillment?.trackingNumber || "";
  const trackingUrl = trackingNumber 
    ? `https://track.manoonoils.com/${trackingNumber}` 
    : "https://manoonoils.com";

  // Compile greeting with customer name
  const greeting = Handlebars.compile(t.greeting)({ customerName });
  
  // Customer email data
  const customerData = {
    ...t,
    greeting,
    orderNumber: order.number || order.id,
    customerName,
    orderDate,
    trackingNumber,
    trackingUrl,
    items
  };

  // Admin email data (English)
  const adminData = {
    orderNumber: order.number || order.id,
    customerName,
    customerEmail: order.userEmail || "",
    orderDate,
    trackingNumber,
    phone: order.shippingAddress?.phone || "",
    items
  };

  return {
    customerSubject: Handlebars.compile(t.subject)({ orderNumber: order.number || order.id }),
    customerHtml: compileCustomerEmail(customerData),
    adminSubject: `Order Shipped #${order.number || order.id}`,
    adminHtml: compileAdminEmail(adminData)
  };
}
