/**
 * Email Builder Service - Compiles email templates with data
 * Handles template compilation and rendering
 */

import Handlebars from "handlebars";
import type { SaleorOrder, EmailResult } from "../types";
import { OrderTransformerService } from "./orderTransformerService";
import {
  emailTranslations,
  adminEmailTranslations,
  adminPaymentConfig,
  DEFAULT_LANGUAGE,
} from "../config";

// 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="{{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>{{statusLabel}}</strong> {{orderStatus}}</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="background:#f9f9f9;padding:15px;border-radius:8px;margin-bottom:20px;">
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>{{subtotalLabel}}</strong> {{subtotal}}</p>
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>{{shippingLabel}}</strong> {{shipping}}</p>
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>{{taxLabel}}</strong> {{tax}}</p>
      <hr style="border-color:#e0e0e0;margin:10px 0;">
      <p style="font-size:16px;font-weight:bold;color:#1a1a1a;margin:0;"><strong>{{totalLabel}}</strong> {{total}}</p>
    </div>
    
    {{#if shippingAddress}}
    <div style="margin-bottom:20px;">
      <p style="font-size:16px;font-weight:bold;color:#1a1a1a;margin-bottom:10px;">{{shippingAddressLabel}}</p>
      <p style="font-size:14px;color:#666;margin:0;white-space:pre-line;">{{shippingAddress}}</p>
      <p style="font-size:14px;color:#666;margin:8px 0 0 0;"><strong>{{phoneLabel}}</strong> {{#if phone}}{{phone}}{{else}}{{phoneNotProvided}}{{/if}}</p>
    </div>
    {{/if}}
    
    <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;">{{viewOrderButton}}</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>
`;

// 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;">{{adminTitle}}</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;">{{adminOrderLabel}} #{{orderNumber}}</h3>
      <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 0 8px 0;"><strong>{{statusLabel}}</strong> {{orderStatus}}</p>
      <p style="font-size:14px;color:#333;margin:0;"><strong>{{paymentLabel}}</strong> {{paymentMethod}}</p>
    </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;">{{customerLabel}}</h3>
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>{{nameLabel}}</strong> {{customerName}}</p>
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>{{emailLabel}}</strong> {{customerEmail}}</p>
      <p style="font-size:14px;color:#333;margin:0;"><strong>{{phoneLabel}}</strong> {{#if phone}}{{phone}}{{else}}{{phoneNotProvided}}{{/if}}</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="background:#f9f9f9;padding:15px;border-radius:8px;margin-bottom:20px;">
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>{{subtotalLabel}}</strong> {{subtotal}}</p>
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>{{shippingLabel}}</strong> {{shipping}}</p>
      <p style="font-size:14px;color:#333;margin:0 0 8px 0;"><strong>{{taxLabel}}</strong> {{tax}}</p>
      <hr style="border-color:#e0e0e0;margin:10px 0;">
      <p style="font-size:16px;font-weight:bold;color:#1a1a1a;margin:0;"><strong>{{totalLabel}}</strong> {{total}}</p>
    </div>
    
    {{#if shippingAddress}}
    <div style="margin-bottom:20px;">
      <p style="font-size:16px;font-weight:bold;color:#1a1a1a;margin-bottom:10px;">{{shippingAddressLabel}}</p>
      <p style="font-size:14px;color:#666;margin:0;white-space:pre-line;">{{shippingAddress}}</p>
    </div>
    {{/if}}
    
    <div style="text-align:center;margin:20px 0;">
      <a href="{{dashboardUrl}}" style="display:inline-block;background:#000;color:white;padding:12px 30px;border-radius:4px;text-decoration:none;font-size:14px;font-weight:bold;">{{dashboardButton}}</a>
    </div>
  </div>
</body>
</html>
`;

export class EmailBuilderService {
  private static compileCustomerEmail = Handlebars.compile(customerEmailTemplate);
  private static compileAdminEmail = Handlebars.compile(adminEmailTemplate);

  /**
   * Build order created emails (customer + admin)
   */
  static buildOrderCreatedEmails(
    order: SaleorOrder,
    config: {
      companyLogoUrl: string;
      companyName: string;
      storefrontUrl: string;
      dashboardUrl: string;
    }
  ): EmailResult {
    const languageCode = OrderTransformerService.getLanguageCode(order);
    const translations = emailTranslations[languageCode] || emailTranslations[DEFAULT_LANGUAGE];

    // Compile greeting and subject with Handlebars
    const greeting = Handlebars.compile(translations.greeting)({
      customerName: OrderTransformerService.extractCustomerName(order),
    });
    const subject = Handlebars.compile(translations.subject)({
      orderNumber: order.number || order.id,
    });

    // Build customer email data
    const customerData = {
      ...OrderTransformerService.transformToEmailData(order, translations),
      greeting,
      subject,
      companyLogoUrl: config.companyLogoUrl,
      storefrontUrl: config.storefrontUrl,
    };

    // Build admin email data
    const adminTranslationsRecord: Record<string, string> = {
      adminTitle: adminEmailTranslations.adminTitle,
      adminOrderLabel: adminEmailTranslations.adminOrderLabel,
      customerLabel: adminEmailTranslations.customerLabel,
      nameLabel: adminEmailTranslations.nameLabel,
      emailLabel: adminEmailTranslations.emailLabel,
      dashboardButton: adminEmailTranslations.dashboardButton,
    };
    
    const adminData = {
      ...OrderTransformerService.transformToAdminEmailData(
        order,
        translations,
        adminTranslationsRecord
      ),
      ...adminPaymentConfig,
      dashboardUrl: config.dashboardUrl,
      companyLogoUrl: config.companyLogoUrl,
    };

    return {
      customerSubject: subject,
      customerHtml: this.compileCustomerEmail(customerData),
      adminSubject: `${adminEmailTranslations.adminTitle} #${order.number || order.id}`,
      adminHtml: this.compileAdminEmail(adminData),
    };
  }
}
