/**
 * Onboarding and Invoice Email Templates
 */

import { sendEmail } from "./email";

interface EmailTemplate {
  subject: string;
  html: string;
  text: string;
}

/**
 * Send Onboarding Congratulations Email
 */
export async function sendOnboardingCongratulationsEmail(
  email: string,
  name: string,
  companyName: string,
  packageName: string,
  trialDays: number,
  language: "ar" | "en",
): Promise<boolean> {
  try {
    console.log("[Onboarding Email] Creating congratulations email", {
      email,
      name,
      companyName,
      packageName,
      trialDays,
      language,
    });

    const isArabic = language === "ar";
    const subject = isArabic
      ? `🎉 مرحباً بك في Mawidi - ${name}!`
      : `🎉 Welcome to Mawidi - ${name}!`;

    const html = `<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; background: #f9fafb; margin: 0; padding: 20px;">
  <div style="max-width: 600px; margin: 0 auto; background: #fff; border-radius: 12px; overflow: hidden;">
    <div style="background: linear-gradient(135deg, #10b981, #059669); padding: 40px; text-align: center;">
      <h1 style="color: #fff; font-size: 32px; margin: 0;">Mawidi</h1>
      <p style="color: #d1fae5; margin-top: 8px;">${isArabic ? "منصة إدارة المواعيد" : "Appointment Management"}</p>
    </div>
    <div style="padding: 40px;">
      <h2 style="font-size: 24px; color: #1f2937; margin-bottom: 20px;">
        ${isArabic ? `مرحباً ${name}! 🎉` : `Welcome ${name}! 🎉`}
      </h2>
      <p style="font-size: 16px; line-height: 1.6; color: #4b5563;">
        ${isArabic ? "تهانينا! لقد أكملت التسجيل بنجاح في Mawidi." : "Congratulations! You have successfully completed signup at Mawidi."}
      </p>
      <div style="background: #f0fdf4; border-left: 4px solid #10b981; padding: 20px; margin: 30px 0; border-radius: 8px;">
        <div style="margin-bottom: 12px;"><strong style="color: #059669;">${isArabic ? "البريد:" : "Email:"}</strong> ${email}</div>
        <div style="margin-bottom: 12px;"><strong style="color: #059669;">${isArabic ? "الشركة:" : "Company:"}</strong> ${companyName}</div>
        <div><strong style="color: #059669;">${isArabic ? "الباقة:" : "Package:"}</strong> ${packageName}</div>
      </div>
      <div style="background: linear-gradient(135deg, #eff6ff, #dbeafe); border-radius: 12px; padding: 24px; text-align: center; margin: 30px 0;">
        <div style="background: #3b82f6; color: #fff; padding: 8px 20px; border-radius: 20px; display: inline-block; font-weight: 700; margin-bottom: 12px;">
          ${isArabic ? "✨ تجربة مجانية" : "✨ FREE TRIAL"}
        </div>
        <p style="font-size: 18px; font-weight: 600; color: #1e40af; margin: 0;">
          ${isArabic ? `${trialDays} يوم تجريبي مجاني` : `${trialDays} Days Free Trial`}
        </p>
      </div>
      <div style="text-align: center; margin: 30px 0;">
        <a href="${process.env.NEXT_PUBLIC_APP_URL || "http://localhost:9000"}/${language}/dashboard"
           style="background: #10b981; color: #fff; padding: 16px 40px; border-radius: 8px; text-decoration: none; font-weight: 700; display: inline-block;">
          ${isArabic ? "لوحة التحكم" : "Go to Dashboard"}
        </a>
      </div>
    </div>
    <div style="background: #f9fafb; padding: 30px; text-align: center;">
      <p style="font-size: 14px; color: #6b7280;">© 2025 Mawidi</p>
    </div>
  </div>
</body>
</html>`;

    const text = `${isArabic ? "مرحباً" : "Welcome"} ${name}!\n\n${isArabic ? "حسابك:" : "Account:"}\n- Email: ${email}\n- Company: ${companyName}\n- Package: ${packageName}\n\n✨ Trial: ${trialDays} days\n\n© 2025 Mawidi`;

    const template = { subject, html, text };

    console.log("[Onboarding Email] Sending congratulations email to", email);
    const result = await sendEmail(email, template);

    if (result) {
      console.log(
        "[Onboarding Email] ✅ Congratulations email sent successfully",
      );
    } else {
      console.log("[Onboarding Email] ❌ Failed to send congratulations email");
    }

    return result;
  } catch (error) {
    console.error(
      "[Onboarding Email] Exception sending congratulations email:",
      error,
    );
    return false;
  }
}

/**
 * Send Invoice Email
 */
export async function sendInvoiceEmail(
  email: string,
  name: string,
  companyName: string,
  invoiceData: {
    invoiceNumber: string;
    packageName: string;
    currency: string;
    setupFee: number;
    recurringAmount: number;
    trialEndsDate: string;
    nextBillingDate: string;
  },
  language: "ar" | "en",
): Promise<boolean> {
  try {
    console.log("[Invoice Email] Creating invoice email", {
      email,
      name,
      companyName,
      invoiceNumber: invoiceData.invoiceNumber,
      setupFee: invoiceData.setupFee,
      recurringAmount: invoiceData.recurringAmount,
      currency: invoiceData.currency,
      language,
    });

    const isArabic = language === "ar";
    const subject = isArabic
      ? `فاتورة Mawidi #${invoiceData.invoiceNumber}`
      : `Mawidi Invoice #${invoiceData.invoiceNumber}`;

    const totalPaid = invoiceData.setupFee;
    const today = new Date().toLocaleDateString(isArabic ? "ar-SA" : "en-US");

    const html = `<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 20px; background: #f9fafb;">
  <div style="max-width: 700px; margin: 0 auto; background: #fff; border-radius: 12px; overflow: hidden;">
    <div style="background: #10b981; padding: 30px; text-align: center;">
      <h1 style="color: #fff; margin: 0;">Mawidi</h1>
      <p style="color: #d1fae5; margin-top: 8px;">${isArabic ? "فاتورة" : "Invoice"}</p>
    </div>
    <div style="padding: 40px;">
      <h2 style="font-size: 24px; color: #1f2937;">${isArabic ? "فاتورة #" : "Invoice #"}${invoiceData.invoiceNumber}</h2>
      <p style="color: #6b7280;">${isArabic ? "التاريخ:" : "Date:"} ${today}</p>
      <p style="color: #10b981; font-weight: 700; margin: 20px 0;">${isArabic ? "مدفوعة ✓" : "PAID ✓"}</p>
      <div style="margin: 30px 0; padding: 20px; background: #f9fafb; border-radius: 8px;">
        <p style="font-weight: 600; color: #6b7280; margin-bottom: 8px;">${isArabic ? "إلى:" : "TO:"}</p>
        <p style="font-size: 18px; font-weight: 700; margin: 4px 0;">${companyName}</p>
        <p style="margin: 2px 0;">${name}</p>
        <p style="margin: 2px 0;">${email}</p>
      </div>
      <table style="width: 100%; border-collapse: collapse; margin: 20px 0;">
        <tr style="background: #f9fafb;">
          <th style="padding: 12px; text-align: left; border-bottom: 2px solid #e5e7eb;">${isArabic ? "البند" : "Item"}</th>
          <th style="padding: 12px; text-align: right; border-bottom: 2px solid #e5e7eb;">${isArabic ? "المبلغ" : "Amount"}</th>
        </tr>
        <tr>
          <td style="padding: 16px 12px; border-bottom: 1px solid #f3f4f6;">${invoiceData.packageName} ${isArabic ? "(شهري)" : "(Monthly)"}</td>
          <td style="padding: 16px 12px; border-bottom: 1px solid #f3f4f6; text-align: right; font-weight: 600;">${invoiceData.currency} ${invoiceData.recurringAmount.toFixed(2)}</td>
        </tr>
        ${
          invoiceData.setupFee > 0
            ? `<tr>
          <td style="padding: 16px 12px; border-bottom: 1px solid #f3f4f6;">${isArabic ? "رسوم الإعداد" : "Setup Fee"}</td>
          <td style="padding: 16px 12px; border-bottom: 1px solid #f3f4f6; text-align: right; font-weight: 600;">${invoiceData.currency} ${invoiceData.setupFee.toFixed(2)}</td>
        </tr>`
            : ""
        }
        <tr style="background: #f0fdf4;">
          <td style="padding: 20px 12px; font-weight: 700; font-size: 18px;">${isArabic ? "المجموع" : "Total"}</td>
          <td style="padding: 20px 12px; text-align: right; font-weight: 700; font-size: 18px; color: #10b981;">${invoiceData.currency} ${totalPaid.toFixed(2)}</td>
        </tr>
      </table>
      <div style="background: #eff6ff; border: 2px solid #93c5fd; border-radius: 12px; padding: 20px; text-align: center; margin: 20px 0;">
        <p style="color: #1e40af; font-weight: 600; margin: 0;">
          🎁 ${isArabic ? `التجربة تنتهي: ${invoiceData.trialEndsDate}` : `Trial ends: ${invoiceData.trialEndsDate}`}
        </p>
      </div>
      <div style="background: #fef3c7; border-radius: 8px; padding: 16px; margin: 20px 0;">
        <p style="font-weight: 600; color: #92400e; margin-bottom: 8px;">${isArabic ? "الدفعة التالية:" : "Next Billing:"}</p>
        <p style="font-size: 18px; font-weight: 700; color: #78350f; margin: 0;">${invoiceData.nextBillingDate}</p>
      </div>
    </div>
    <div style="background: #1f2937; padding: 30px; text-align: center; color: #d1d5db;">
      <p style="margin: 6px 0;">© 2025 Mawidi</p>
      <p style="margin: 6px 0;">support@mawidi.com</p>
    </div>
  </div>
</body>
</html>`;

    const text = `Invoice #${invoiceData.invoiceNumber}\n\n${companyName}\n${name}\n${email}\n\n${invoiceData.packageName}: ${invoiceData.currency} ${invoiceData.recurringAmount}/mo\n${invoiceData.setupFee > 0 ? `Setup Fee: ${invoiceData.currency} ${invoiceData.setupFee}\n` : ""}Total: ${invoiceData.currency} ${totalPaid}\n\nTrial ends: ${invoiceData.trialEndsDate}\nNext billing: ${invoiceData.nextBillingDate}`;

    const template = { subject, html, text };

    console.log("[Invoice Email] Sending invoice email to", email);
    const result = await sendEmail(email, template);

    if (result) {
      console.log("[Invoice Email] ✅ Invoice email sent successfully");
    } else {
      console.log("[Invoice Email] ❌ Failed to send invoice email");
    }

    return result;
  } catch (error) {
    console.error("[Invoice Email] Exception sending invoice email:", error);
    return false;
  }
}
