/**
 * Quotation Email Templates
 *
 * Bilingual templates for quotation notifications:
 * - Sent: New quotation notification with summary
 * - Reminder: Payment reminder before/on due date
 * - Overdue: Overdue warning with penalty info
 */

import type { EmailTemplate } from "../types";

// =============================================================================
// Quotation Sent Email
// =============================================================================

export interface QuotationSentEmailParams {
  quotationNumber: string;
  title: string;
  customerName: string;
  total: number;
  currency: string;
  dueDate?: string;
  portalUrl: string;
  items: Array<{ description: string; quantity: number; unitPrice: number; total: number }>;
  lang: "ar" | "en";
}

export function createQuotationSentEmail(
  params: QuotationSentEmailParams,
): EmailTemplate {
  const {
    quotationNumber,
    title,
    customerName,
    total,
    currency,
    dueDate,
    portalUrl,
    items,
    lang,
  } = params;

  const isAr = lang === "ar";
  const fmt = new Intl.NumberFormat(isAr ? "ar-SA" : "en-US", {
    style: "currency",
    currency: currency.toUpperCase(),
  });
  const formattedTotal = fmt.format(total);

  const subject = isAr
    ? `عرض سعر جديد #${quotationNumber} - ${title}`
    : `New Quotation #${quotationNumber} - ${title}`;

  const itemRows = items
    .map(
      (item) => `
      <tr>
        <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; font-size: 14px; color: #374151;">${item.description}</td>
        <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; font-size: 14px; color: #6b7280; text-align: center;">${item.quantity}</td>
        <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; font-size: 14px; color: #6b7280; text-align: ${isAr ? "left" : "right"};">${fmt.format(item.unitPrice)}</td>
        <td style="padding: 10px 12px; border-bottom: 1px solid #e5e7eb; font-size: 14px; color: #111827; font-weight: 600; text-align: ${isAr ? "left" : "right"};">${fmt.format(item.total)}</td>
      </tr>`,
    )
    .join("");

  const dueDateRow = dueDate
    ? `<div style="margin: 12px 0; display: flex; align-items: center; gap: 10px;">
        <span style="font-weight: bold; color: #059669; min-width: 120px;">${isAr ? "تاريخ الاستحقاق:" : "Due Date:"}</span>
        <span>${dueDate}</span>
       </div>`
    : "";

  const html = `
    <!DOCTYPE html>
    <html ${isAr ? 'dir="rtl" lang="ar"' : 'lang="en"'}>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; background: #f3f4f6; margin: 0; padding: 20px;">
      <div style="max-width: 600px; margin: 0 auto;">
        <div style="background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); color: white; padding: 30px; text-align: center; border-radius: 12px 12px 0 0;">
          <h1 style="margin: 0; font-size: 22px;">${isAr ? "عرض سعر جديد" : "New Quotation"}</h1>
          <p style="margin: 8px 0 0 0; opacity: 0.9; font-size: 14px;">#${quotationNumber}</p>
        </div>
        <div style="background: white; padding: 30px; border-radius: 0 0 12px 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
          <p style="font-size: 16px;">${isAr ? `عزيزي ${customerName}،` : `Dear ${customerName},`}</p>
          <p>${isAr ? "يسعدنا إرسال عرض السعر التالي لمراجعتكم:" : "We are pleased to send you the following quotation for your review:"}</p>

          <div style="background: #f0fdf4; padding: 16px; margin: 20px 0; border-radius: 8px; border: 2px solid #22c55e;">
            <div style="margin: 8px 0;">
              <span style="font-weight: bold; color: #059669;">${isAr ? "العنوان:" : "Title:"}</span>
              <span style="margin-${isAr ? "right" : "left"}: 8px;">${title}</span>
            </div>
            ${dueDateRow}
          </div>

          <table style="width: 100%; border-collapse: collapse; margin: 20px 0;">
            <thead>
              <tr style="background: #f9fafb;">
                <th style="padding: 10px 12px; text-align: ${isAr ? "right" : "left"}; font-size: 12px; text-transform: uppercase; color: #6b7280; border-bottom: 2px solid #e5e7eb;">${isAr ? "البند" : "Item"}</th>
                <th style="padding: 10px 12px; text-align: center; font-size: 12px; text-transform: uppercase; color: #6b7280; border-bottom: 2px solid #e5e7eb;">${isAr ? "الكمية" : "Qty"}</th>
                <th style="padding: 10px 12px; text-align: ${isAr ? "left" : "right"}; font-size: 12px; text-transform: uppercase; color: #6b7280; border-bottom: 2px solid #e5e7eb;">${isAr ? "السعر" : "Price"}</th>
                <th style="padding: 10px 12px; text-align: ${isAr ? "left" : "right"}; font-size: 12px; text-transform: uppercase; color: #6b7280; border-bottom: 2px solid #e5e7eb;">${isAr ? "الإجمالي" : "Total"}</th>
              </tr>
            </thead>
            <tbody>
              ${itemRows}
            </tbody>
          </table>

          <div style="background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%); padding: 20px; border-radius: 12px; margin: 20px 0; text-align: center; border: 2px solid #22c55e;">
            <p style="margin: 0 0 5px 0; color: #166534; font-size: 14px;">${isAr ? "الإجمالي" : "Total Amount"}</p>
            <div style="font-size: 28px; font-weight: bold; color: #15803d; margin: 8px 0;">${formattedTotal}</div>
          </div>

          <div style="text-align: center; margin: 30px 0;">
            <a href="${portalUrl}" style="display: inline-block; background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); color: white; padding: 16px 48px; text-decoration: none; border-radius: 8px; font-weight: bold; font-size: 16px; box-shadow: 0 4px 6px rgba(34, 197, 94, 0.3);">
              ${isAr ? "عرض عرض السعر" : "View Quotation"}
            </a>
          </div>

          <p style="color: #6b7280; font-size: 13px;">${isAr ? "يمكنك مراجعة التفاصيل الكاملة وقبول أو رفض عرض السعر من خلال الرابط أعلاه." : "You can review the full details and accept or decline this quotation through the link above."}</p>

          <p>${isAr ? "مع أطيب التحيات،" : "Best regards,"}<br>${isAr ? "فريق Mawidi" : "The Mawidi Team"}</p>
        </div>
        <div style="text-align: center; margin-top: 20px; color: #6b7280; font-size: 13px;">
          <p>&copy; ${new Date().getFullYear()} Mawidi. ${isAr ? "جميع الحقوق محفوظة." : "All rights reserved."}</p>
        </div>
      </div>
    </body>
    </html>`;

  const itemsText = items
    .map((item) => `- ${item.description} x${item.quantity} = ${fmt.format(item.total)}`)
    .join("\n");

  const text = isAr
    ? `عرض سعر جديد #${quotationNumber}

عزيزي ${customerName}،

يسعدنا إرسال عرض السعر التالي:
العنوان: ${title}
${dueDate ? `تاريخ الاستحقاق: ${dueDate}` : ""}

البنود:
${itemsText}

الإجمالي: ${formattedTotal}

عرض التفاصيل: ${portalUrl}

مع أطيب التحيات،
فريق Mawidi`
    : `New Quotation #${quotationNumber}

Dear ${customerName},

We are pleased to send you the following quotation:
Title: ${title}
${dueDate ? `Due Date: ${dueDate}` : ""}

Items:
${itemsText}

Total: ${formattedTotal}

View Quotation: ${portalUrl}

Best regards,
The Mawidi Team`;

  return { subject, html, text };
}

// =============================================================================
// Quotation Reminder Email
// =============================================================================

export interface QuotationReminderEmailParams {
  quotationNumber: string;
  customerName: string;
  total: number;
  amountPaid: number;
  remaining: number;
  dueDate: string;
  daysUntilDue: number;
  portalUrl: string;
  lang: "ar" | "en";
}

export function createQuotationReminderEmail(
  params: QuotationReminderEmailParams,
): EmailTemplate {
  const {
    quotationNumber,
    customerName,
    total,
    amountPaid,
    remaining,
    dueDate,
    daysUntilDue,
    portalUrl,
    lang,
  } = params;

  const isAr = lang === "ar";
  const currency = "QAR"; // Default for reminder context
  const fmt = new Intl.NumberFormat(isAr ? "ar-SA" : "en-US", {
    style: "currency",
    currency,
  });

  const isOverdue = daysUntilDue < 0;
  const absDays = Math.abs(daysUntilDue);

  const subject = isAr
    ? isOverdue
      ? `تنبيه: دفعة متأخرة لعرض السعر #${quotationNumber}`
      : `تذكير: دفعة مستحقة خلال ${absDays} ${absDays === 1 ? "يوم" : "أيام"} - #${quotationNumber}`
    : isOverdue
      ? `Alert: Payment Overdue for Quotation #${quotationNumber}`
      : `Reminder: Payment Due in ${absDays} Day${absDays !== 1 ? "s" : ""} - #${quotationNumber}`;

  const urgencyColor = isOverdue ? "#dc2626" : daysUntilDue <= 3 ? "#f59e0b" : "#22c55e";

  const html = `
    <!DOCTYPE html>
    <html ${isAr ? 'dir="rtl" lang="ar"' : 'lang="en"'}>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; background: #f3f4f6; margin: 0; padding: 20px;">
      <div style="max-width: 600px; margin: 0 auto;">
        <div style="background: ${urgencyColor}; color: white; padding: 30px; text-align: center; border-radius: 12px 12px 0 0;">
          <h1 style="margin: 0; font-size: 22px;">
            ${isAr
              ? isOverdue ? "دفعة متأخرة" : "تذكير بالدفع"
              : isOverdue ? "Payment Overdue" : "Payment Reminder"}
          </h1>
          <p style="margin: 8px 0 0 0; opacity: 0.9; font-size: 18px; font-weight: bold;">
            ${isAr
              ? isOverdue ? `متأخر ${absDays} ${absDays === 1 ? "يوم" : "أيام"}` : `مستحق خلال ${absDays} ${absDays === 1 ? "يوم" : "أيام"}`
              : isOverdue ? `${absDays} Day${absDays !== 1 ? "s" : ""} Overdue` : `Due in ${absDays} Day${absDays !== 1 ? "s" : ""}`}
          </p>
        </div>
        <div style="background: white; padding: 30px; border-radius: 0 0 12px 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
          <p>${isAr ? `عزيزي ${customerName}،` : `Dear ${customerName},`}</p>
          <p>${isAr
            ? `هذا تذكير بشأن الدفعة المستحقة لعرض السعر #${quotationNumber}.`
            : `This is a reminder regarding the payment due for Quotation #${quotationNumber}.`}</p>

          <div style="background: #f9fafb; padding: 20px; margin: 20px 0; border-radius: 8px; border: 1px solid #e5e7eb;">
            <div style="display: flex; justify-content: space-between; margin: 8px 0; font-size: 14px;">
              <span style="color: #6b7280;">${isAr ? "الإجمالي:" : "Total:"}</span>
              <span style="font-weight: 600;">${fmt.format(total)}</span>
            </div>
            ${amountPaid > 0 ? `
            <div style="display: flex; justify-content: space-between; margin: 8px 0; font-size: 14px;">
              <span style="color: #16a34a;">${isAr ? "المدفوع:" : "Paid:"}</span>
              <span style="color: #16a34a;">${fmt.format(amountPaid)}</span>
            </div>` : ""}
            <div style="display: flex; justify-content: space-between; margin: 8px 0; font-size: 14px; padding-top: 8px; border-top: 1px solid #e5e7eb;">
              <span style="font-weight: bold;">${isAr ? "المتبقي:" : "Remaining:"}</span>
              <span style="font-weight: bold; color: ${urgencyColor};">${fmt.format(remaining)}</span>
            </div>
            <div style="display: flex; justify-content: space-between; margin: 8px 0; font-size: 14px;">
              <span style="color: #6b7280;">${isAr ? "تاريخ الاستحقاق:" : "Due Date:"}</span>
              <span style="color: ${isOverdue ? "#dc2626" : "#111827"}; font-weight: 600;">${dueDate}</span>
            </div>
          </div>

          <div style="text-align: center; margin: 30px 0;">
            <a href="${portalUrl}" style="display: inline-block; background: ${urgencyColor}; color: white; padding: 16px 48px; text-decoration: none; border-radius: 8px; font-weight: bold; font-size: 16px;">
              ${isAr ? "ادفع الآن" : "Pay Now"}
            </a>
          </div>

          <p>${isAr ? "مع أطيب التحيات،" : "Best regards,"}<br>${isAr ? "فريق Mawidi" : "The Mawidi Team"}</p>
        </div>
        <div style="text-align: center; margin-top: 20px; color: #6b7280; font-size: 13px;">
          <p>&copy; ${new Date().getFullYear()} Mawidi. ${isAr ? "جميع الحقوق محفوظة." : "All rights reserved."}</p>
        </div>
      </div>
    </body>
    </html>`;

  const text = isAr
    ? `تذكير بالدفع - عرض السعر #${quotationNumber}

عزيزي ${customerName}،

${isOverdue ? `دفعتك متأخرة ${absDays} أيام.` : `دفعتك مستحقة خلال ${absDays} أيام.`}

الإجمالي: ${fmt.format(total)}
${amountPaid > 0 ? `المدفوع: ${fmt.format(amountPaid)}\n` : ""}المتبقي: ${fmt.format(remaining)}
تاريخ الاستحقاق: ${dueDate}

ادفع الآن: ${portalUrl}

فريق Mawidi`
    : `Payment Reminder - Quotation #${quotationNumber}

Dear ${customerName},

${isOverdue ? `Your payment is ${absDays} day${absDays !== 1 ? "s" : ""} overdue.` : `Your payment is due in ${absDays} day${absDays !== 1 ? "s" : ""}.`}

Total: ${fmt.format(total)}
${amountPaid > 0 ? `Paid: ${fmt.format(amountPaid)}\n` : ""}Remaining: ${fmt.format(remaining)}
Due Date: ${dueDate}

Pay Now: ${portalUrl}

The Mawidi Team`;

  return { subject, html, text };
}

// =============================================================================
// Quotation Overdue Email
// =============================================================================

export interface QuotationOverdueEmailParams {
  quotationNumber: string;
  customerName: string;
  total: number;
  amountPaid: number;
  penaltyAmount: number;
  grandTotal: number;
  dueDate: string;
  daysOverdue: number;
  portalUrl: string;
  lang: "ar" | "en";
}

export function createQuotationOverdueEmail(
  params: QuotationOverdueEmailParams,
): EmailTemplate {
  const {
    quotationNumber,
    customerName,
    total,
    amountPaid,
    penaltyAmount,
    grandTotal,
    dueDate,
    daysOverdue,
    portalUrl,
    lang,
  } = params;

  const isAr = lang === "ar";
  const currency = "QAR";
  const fmt = new Intl.NumberFormat(isAr ? "ar-SA" : "en-US", {
    style: "currency",
    currency,
  });

  const subject = isAr
    ? `عاجل: دفعة متأخرة مع غرامة - عرض السعر #${quotationNumber}`
    : `Urgent: Overdue Payment with Penalty - Quotation #${quotationNumber}`;

  const html = `
    <!DOCTYPE html>
    <html ${isAr ? 'dir="rtl" lang="ar"' : 'lang="en"'}>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; background: #f3f4f6; margin: 0; padding: 20px;">
      <div style="max-width: 600px; margin: 0 auto;">
        <div style="background: #dc2626; color: white; padding: 30px; text-align: center; border-radius: 12px 12px 0 0;">
          <h1 style="margin: 0; font-size: 22px;">${isAr ? "دفعة متأخرة - إجراء مطلوب" : "Payment Overdue - Action Required"}</h1>
          <p style="margin: 8px 0 0 0; font-size: 18px; font-weight: bold;">
            ${daysOverdue} ${isAr ? (daysOverdue === 1 ? "يوم تأخير" : "أيام تأخير") : `Day${daysOverdue !== 1 ? "s" : ""} Overdue`}
          </p>
        </div>
        <div style="background: white; padding: 30px; border-radius: 0 0 12px 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
          <p>${isAr ? `عزيزي ${customerName}،` : `Dear ${customerName},`}</p>
          <p style="color: #dc2626; font-weight: 600;">
            ${isAr
              ? `دفعة عرض السعر #${quotationNumber} متأخرة ${daysOverdue} ${daysOverdue === 1 ? "يوم" : "أيام"} عن تاريخ الاستحقاق ${dueDate}. تم تطبيق غرامة تأخير.`
              : `Payment for Quotation #${quotationNumber} is ${daysOverdue} day${daysOverdue !== 1 ? "s" : ""} past the due date of ${dueDate}. A late penalty has been applied.`}
          </p>

          <div style="background: #fef2f2; padding: 20px; margin: 20px 0; border-radius: 8px; border: 2px solid #dc2626;">
            <div style="margin: 8px 0; font-size: 14px;">
              <span style="color: #6b7280;">${isAr ? "الإجمالي الأصلي:" : "Original Total:"}</span>
              <span style="float: ${isAr ? "left" : "right"};">${fmt.format(total)}</span>
            </div>
            ${amountPaid > 0 ? `
            <div style="margin: 8px 0; font-size: 14px;">
              <span style="color: #16a34a;">${isAr ? "المدفوع:" : "Paid:"}</span>
              <span style="float: ${isAr ? "left" : "right"}; color: #16a34a;">-${fmt.format(amountPaid)}</span>
            </div>` : ""}
            <div style="margin: 8px 0; font-size: 14px; color: #dc2626; font-weight: bold;">
              <span>${isAr ? "غرامة التأخير:" : "Late Penalty:"}</span>
              <span style="float: ${isAr ? "left" : "right"};">+${fmt.format(penaltyAmount)}</span>
            </div>
            <div style="margin: 12px 0 0 0; padding-top: 12px; border-top: 2px solid #dc2626; font-size: 18px; font-weight: bold;">
              <span>${isAr ? "المطلوب الآن:" : "Amount Due Now:"}</span>
              <span style="float: ${isAr ? "left" : "right"}; color: #dc2626;">${fmt.format(grandTotal - amountPaid)}</span>
            </div>
          </div>

          <div style="background: #fefce8; padding: 15px; border-radius: 6px; margin: 20px 0; border-${isAr ? "right" : "left"}: 4px solid #f59e0b;">
            <p style="margin: 0; font-size: 14px;">
              ${isAr
                ? "يرجى تسوية هذه الدفعة في أقرب وقت لتجنب غرامات إضافية."
                : "Please settle this payment as soon as possible to avoid additional penalties."}
            </p>
          </div>

          <div style="text-align: center; margin: 30px 0;">
            <a href="${portalUrl}" style="display: inline-block; background: #dc2626; color: white; padding: 16px 48px; text-decoration: none; border-radius: 8px; font-weight: bold; font-size: 16px; box-shadow: 0 4px 6px rgba(220, 38, 38, 0.3);">
              ${isAr ? "ادفع الآن" : "Pay Now"}
            </a>
          </div>

          <p>${isAr ? "مع أطيب التحيات،" : "Best regards,"}<br>${isAr ? "فريق Mawidi" : "The Mawidi Team"}</p>
        </div>
        <div style="text-align: center; margin-top: 20px; color: #6b7280; font-size: 13px;">
          <p>&copy; ${new Date().getFullYear()} Mawidi. ${isAr ? "جميع الحقوق محفوظة." : "All rights reserved."}</p>
        </div>
      </div>
    </body>
    </html>`;

  const text = isAr
    ? `عاجل: دفعة متأخرة - عرض السعر #${quotationNumber}

عزيزي ${customerName}،

دفعتك متأخرة ${daysOverdue} أيام (تاريخ الاستحقاق: ${dueDate}).

الإجمالي الأصلي: ${fmt.format(total)}
${amountPaid > 0 ? `المدفوع: ${fmt.format(amountPaid)}\n` : ""}غرامة التأخير: +${fmt.format(penaltyAmount)}
المطلوب الآن: ${fmt.format(grandTotal - amountPaid)}

ادفع الآن: ${portalUrl}

يرجى تسوية هذه الدفعة لتجنب غرامات إضافية.

فريق Mawidi`
    : `Urgent: Overdue Payment - Quotation #${quotationNumber}

Dear ${customerName},

Your payment is ${daysOverdue} day${daysOverdue !== 1 ? "s" : ""} overdue (due: ${dueDate}).

Original Total: ${fmt.format(total)}
${amountPaid > 0 ? `Paid: ${fmt.format(amountPaid)}\n` : ""}Late Penalty: +${fmt.format(penaltyAmount)}
Amount Due Now: ${fmt.format(grandTotal - amountPaid)}

Pay Now: ${portalUrl}

Please settle this payment as soon as possible to avoid additional penalties.

The Mawidi Team`;

  return { subject, html, text };
}
