import { env } from "@/config/env";

/** Branded HTML email — table layout + inline CSS for Gmail/Outlook. */
export function buildOtpEmailHtml(params: {
  fullName: string;
  code: string;
  minutesValid?: number;
}) {
  const brand = env.APP_NAME || "Safar Libya";
  const minutes = params.minutesValid ?? 10;
  const firstName = params.fullName.trim().split(/\s+/)[0] || params.fullName;
  const year = new Date().getFullYear();

  return `<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>${brand}</title>
</head>
<body style="margin:0;padding:0;background:#eef3f6;font-family:'Segoe UI',Tahoma,Arial,sans-serif;-webkit-font-smoothing:antialiased;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#eef3f6;padding:32px 12px;">
    <tr>
      <td align="center">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;background:#ffffff;border-radius:16px;overflow:hidden;box-shadow:0 8px 30px rgba(11,79,108,0.08);">
          <!-- Brand header -->
          <tr>
            <td style="background:linear-gradient(135deg,#0B4F6C 0%,#14668a 55%,#1a7a9c 100%);padding:28px 32px;text-align:center;">
              <p style="margin:0;font-size:26px;font-weight:700;letter-spacing:0.5px;color:#ffffff;">سفر ليبيا</p>
              <p style="margin:6px 0 0;font-size:13px;color:#d7ebea;letter-spacing:1px;">SAFAR LIBYA</p>
            </td>
          </tr>

          <!-- Welcome -->
          <tr>
            <td style="padding:32px 32px 8px;text-align:right;">
              <p style="margin:0 0 8px;font-size:22px;font-weight:700;color:#0B4F6C;">مرحباً ${escapeHtml(firstName)}</p>
              <p style="margin:0;font-size:15px;line-height:1.7;color:#3d4f5c;">
                أهلاً بك في <strong style="color:#0B4F6C;">سفر ليبيا</strong> — منصتك لحجز إقامات موثوقة في تونس بأسعار واضحة.
              </p>
              <p style="margin:14px 0 0;font-size:14px;line-height:1.7;color:#5a6b76;">
                لإكمال تفعيل حسابك، استخدم رمز التحقق التالي:
              </p>
            </td>
          </tr>

          <!-- OTP box -->
          <tr>
            <td style="padding:20px 32px;">
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f8fa;border:1px solid #d5e4eb;border-radius:14px;">
                <tr>
                  <td align="center" style="padding:28px 16px;">
                    <p style="margin:0 0 10px;font-size:12px;font-weight:600;color:#6a7f8c;letter-spacing:1px;text-transform:uppercase;">رمز التحقق</p>
                    <p style="margin:0;font-size:36px;font-weight:700;letter-spacing:10px;color:#0B4F6C;font-family:Consolas,'Courier New',monospace;direction:ltr;">
                      ${params.code}
                    </p>
                    <p style="margin:14px 0 0;font-size:13px;color:#6a7f8c;">صالح لمدة ${minutes} دقائق</p>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- Security note AR -->
          <tr>
            <td style="padding:4px 32px 8px;text-align:right;">
              <p style="margin:0;font-size:13px;line-height:1.7;color:#7a8b96;">
                إذا لم تطلب هذا الرمز، يمكنك تجاهل هذه الرسالة بأمان. لا تشارك الرمز مع أي شخص.
              </p>
            </td>
          </tr>

          <!-- English block -->
          <tr>
            <td style="padding:20px 32px 8px;border-top:1px solid #e8eef2;text-align:left;" dir="ltr">
              <p style="margin:0 0 6px;font-size:16px;font-weight:700;color:#0B4F6C;">Welcome to Safar Libya</p>
              <p style="margin:0;font-size:13px;line-height:1.65;color:#5a6b76;">
                Your verification code is <strong style="letter-spacing:2px;">${params.code}</strong>. It expires in ${minutes} minutes.
              </p>
            </td>
          </tr>

          <!-- Footer -->
          <tr>
            <td style="padding:28px 32px;background:#f7fafb;text-align:center;">
              <p style="margin:0 0 4px;font-size:14px;font-weight:700;color:#0B4F6C;">سفر ليبيا · Safar Libya</p>
              <p style="margin:0;font-size:12px;line-height:1.6;color:#8a9aa5;">
                Trusted Tunisia stays for Libyan travelers
              </p>
              <p style="margin:12px 0 0;font-size:11px;color:#a0aeb8;">
                © ${year} ${brand}. All rights reserved.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}

export function buildOtpEmailText(params: {
  fullName: string;
  code: string;
  minutesValid?: number;
}) {
  const brand = env.APP_NAME || "Safar Libya";
  const minutes = params.minutesValid ?? 10;
  const firstName = params.fullName.trim().split(/\s+/)[0] || params.fullName;

  return [
    `مرحباً ${firstName}،`,
    ``,
    `أهلاً بك في ${brand}.`,
    `رمز التحقق لتفعيل حسابك: ${params.code}`,
    `صالح لمدة ${minutes} دقائق.`,
    ``,
    `إذا لم تطلب هذا الرمز، تجاهل هذه الرسالة.`,
    ``,
    `—`,
    `Welcome to ${brand}.`,
    `Your verification code: ${params.code}`,
    `Valid for ${minutes} minutes.`,
    ``,
    `${brand} — Trusted Tunisia stays for Libyan travelers`,
  ].join("\n");
}

function escapeHtml(value: string) {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function formatMoneyPlain(amount: number, currency: string) {
  const n = Number(amount) || 0;
  return `${currency} ${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

function formatDateAr(value?: Date | string | null) {
  if (!value) return "—";
  const d = typeof value === "string" ? new Date(value) : value;
  if (Number.isNaN(d.getTime())) return "—";
  return new Intl.DateTimeFormat("ar-LY", {
    weekday: "long",
    day: "numeric",
    month: "long",
    year: "numeric",
  }).format(d);
}

export type InvoiceEmailParams = {
  guestName: string;
  guestEmail: string;
  guestPhone?: string | null;
  invoiceNumber: string;
  issuedAt: Date | string;
  propertyTitle: string;
  propertyAddress?: string | null;
  cityName?: string | null;
  hostName?: string | null;
  checkIn: Date | string;
  checkOut: Date | string;
  nights: number;
  guests: number;
  subtotalTnd: number;
  cleaningFeeTnd: number;
  platformFeeTnd: number;
  taxesTnd: number;
  totalTnd: number;
  totalLyd: number;
  exchangeRate: number;
  bookingStatus: string;
  paymentProvider?: string;
  dashboardUrl?: string;
};

export function buildInvoiceEmailHtml(p: InvoiceEmailParams) {
  const brand = env.APP_NAME || "Safar Libya";
  const firstName = p.guestName.trim().split(/\s+/)[0] || p.guestName;
  const year = new Date().getFullYear();
  const statusLabel =
    p.bookingStatus === "CONFIRMED"
      ? "مؤكد / Confirmed"
      : p.bookingStatus === "WAITING_OWNER"
        ? "بانتظار المضيف / Awaiting host"
        : p.bookingStatus;

  const row = (label: string, value: string, bold = false) => `
    <tr>
      <td style="padding:8px 0;font-size:13px;color:#6a7f8c;text-align:right;">${label}</td>
      <td style="padding:8px 0;font-size:13px;color:${bold ? "#0B4F6C" : "#24343f"};font-weight:${bold ? "700" : "500"};text-align:left;" dir="ltr">${value}</td>
    </tr>`;

  return `<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>${brand} — فاتورة ${escapeHtml(p.invoiceNumber)}</title>
</head>
<body style="margin:0;padding:0;background:#eef3f6;font-family:'Segoe UI',Tahoma,Arial,sans-serif;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#eef3f6;padding:28px 12px;">
    <tr>
      <td align="center">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px;background:#ffffff;border-radius:16px;overflow:hidden;box-shadow:0 8px 30px rgba(11,79,108,0.08);">
          <tr>
            <td style="background:#0B4F6C;padding:24px 28px;text-align:center;">
              <p style="margin:0;font-size:22px;font-weight:700;color:#fff;">سفر ليبيا</p>
              <p style="margin:6px 0 0;font-size:12px;letter-spacing:1px;color:#d7ebea;">SAFAR LIBYA — Booking invoice</p>
            </td>
          </tr>

          <tr>
            <td style="padding:28px 28px 8px;text-align:right;">
              <p style="margin:0 0 8px;font-size:22px;font-weight:700;color:#0B4F6C;">مرحباً ${escapeHtml(firstName)}</p>
              <p style="margin:0;font-size:14px;line-height:1.8;color:#3d4f5c;">
                شكراً لثقتك بـ<strong style="color:#0B4F6C;">سفر ليبيا</strong>. هذه فاتورة حجزك الرسمية — احفظها وقدّمها عند تسجيل الوصول.
              </p>
            </td>
          </tr>

          <tr>
            <td style="padding:16px 28px;">
              <table role="presentation" width="100%" style="background:#f4f8fa;border:1px solid #d5e4eb;border-radius:12px;">
                <tr>
                  <td style="padding:16px;text-align:right;width:50%;">
                    <p style="margin:0;font-size:11px;color:#6a7f8c;">رقم الفاتورة</p>
                    <p style="margin:4px 0 0;font-size:14px;font-weight:700;color:#0B4F6C;direction:ltr;text-align:right;">${escapeHtml(p.invoiceNumber)}</p>
                  </td>
                  <td style="padding:16px;text-align:right;width:50%;">
                    <p style="margin:0;font-size:11px;color:#6a7f8c;">تاريخ الإصدار</p>
                    <p style="margin:4px 0 0;font-size:14px;font-weight:600;color:#24343f;">${formatDateAr(p.issuedAt)}</p>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td style="padding:8px 28px 4px;text-align:right;">
              <p style="margin:0 0 8px;font-size:12px;font-weight:700;color:#0B4F6C;letter-spacing:0.5px;">بيانات الضيف</p>
              <p style="margin:0;font-size:15px;font-weight:700;color:#24343f;">${escapeHtml(p.guestName)}</p>
              <p style="margin:4px 0 0;font-size:13px;color:#5a6b76;direction:ltr;text-align:right;">${escapeHtml(p.guestEmail)}</p>
              ${p.guestPhone ? `<p style="margin:2px 0 0;font-size:13px;color:#5a6b76;direction:ltr;text-align:right;">${escapeHtml(p.guestPhone)}</p>` : ""}
            </td>
          </tr>

          <tr>
            <td style="padding:16px 28px 4px;text-align:right;">
              <p style="margin:0 0 8px;font-size:12px;font-weight:700;color:#0B4F6C;">تفاصيل الإقامة</p>
              <p style="margin:0;font-size:15px;font-weight:700;color:#24343f;">${escapeHtml(p.propertyTitle)}</p>
              ${p.cityName ? `<p style="margin:4px 0 0;font-size:13px;color:#5a6b76;">${escapeHtml(p.cityName)}</p>` : ""}
              ${p.propertyAddress ? `<p style="margin:2px 0 0;font-size:12px;color:#7a8b96;">${escapeHtml(p.propertyAddress)}</p>` : ""}
              ${p.hostName ? `<p style="margin:8px 0 0;font-size:13px;color:#5a6b76;">المضيف: ${escapeHtml(p.hostName)}</p>` : ""}
            </td>
          </tr>

          <tr>
            <td style="padding:12px 28px;">
              <table role="presentation" width="100%" style="border:1px solid #e2ebf0;border-radius:12px;">
                <tr>
                  <td style="padding:14px;width:50%;border-bottom:1px solid #e2ebf0;text-align:right;">
                    <p style="margin:0;font-size:11px;color:#6a7f8c;">تاريخ الدخول</p>
                    <p style="margin:4px 0 0;font-size:13px;font-weight:600;color:#0B4F6C;">${formatDateAr(p.checkIn)}</p>
                  </td>
                  <td style="padding:14px;width:50%;border-bottom:1px solid #e2ebf0;border-right:1px solid #e2ebf0;text-align:right;">
                    <p style="margin:0;font-size:11px;color:#6a7f8c;">تاريخ المغادرة</p>
                    <p style="margin:4px 0 0;font-size:13px;font-weight:600;color:#0B4F6C;">${formatDateAr(p.checkOut)}</p>
                  </td>
                </tr>
                <tr>
                  <td style="padding:14px;width:50%;text-align:right;">
                    <p style="margin:0;font-size:11px;color:#6a7f8c;">المدة</p>
                    <p style="margin:4px 0 0;font-size:13px;font-weight:600;">${p.nights} ليالٍ</p>
                  </td>
                  <td style="padding:14px;width:50%;border-right:1px solid #e2ebf0;text-align:right;">
                    <p style="margin:0;font-size:11px;color:#6a7f8c;">الضيوف</p>
                    <p style="margin:4px 0 0;font-size:13px;font-weight:600;">${p.guests}</p>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td style="padding:8px 28px 4px;text-align:right;">
              <p style="margin:0 0 8px;font-size:12px;font-weight:700;color:#0B4F6C;">ملخص الدفع</p>
              <table role="presentation" width="100%">
                ${row("إجمالي الليالي", formatMoneyPlain(p.subtotalTnd, "TND"))}
                ${row("رسوم التنظيف", formatMoneyPlain(p.cleaningFeeTnd, "TND"))}
                ${row("رسوم الخدمة", formatMoneyPlain(p.platformFeeTnd, "TND"))}
                ${row("الضرائب", formatMoneyPlain(p.taxesTnd, "TND"))}
                ${row("الإجمالي (د.ت)", formatMoneyPlain(p.totalTnd, "TND"), true)}
                ${row("المبلغ المدفوع (د.ل)", formatMoneyPlain(p.totalLyd, "LYD"), true)}
              </table>
              <p style="margin:8px 0 0;font-size:12px;color:#7a8b96;">سعر الصرف المقفل: 1 TND = ${p.exchangeRate} LYD</p>
              <p style="margin:4px 0 0;font-size:12px;color:#7a8b96;">حالة الحجز: ${escapeHtml(statusLabel)}</p>
              <p style="margin:4px 0 0;font-size:12px;color:#7a8b96;">طريقة الدفع: ${escapeHtml(p.paymentProvider || "DEMO")}</p>
            </td>
          </tr>

          <tr>
            <td style="padding:20px 28px;">
              <table role="presentation" width="100%" style="background:#eef7f4;border-radius:12px;">
                <tr>
                  <td style="padding:16px;text-align:right;">
                    <p style="margin:0;font-size:13px;line-height:1.8;color:#2f5d52;">
                      نتمنى لك إقامة مريحة ورحلة سعيدة في تونس. لأي استفسار راسلنا على الدعم وسنكون بخدمتك.
                    </p>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          ${
            p.dashboardUrl
              ? `<tr>
            <td style="padding:0 28px 24px;text-align:center;">
              <a href="${escapeHtml(p.dashboardUrl)}" style="display:inline-block;background:#0B4F6C;color:#fff;text-decoration:none;font-size:14px;font-weight:600;padding:12px 22px;border-radius:999px;">عرض الحجز في لوحة التحكم</a>
            </td>
          </tr>`
              : ""
          }

          <tr>
            <td style="padding:22px 28px;background:#f7fafb;text-align:center;">
              <p style="margin:0 0 4px;font-size:14px;font-weight:700;color:#0B4F6C;">سفر ليبيا · Safar Libya</p>
              <p style="margin:0;font-size:12px;color:#8a9aa5;">Trusted Tunisia stays for Libyan travelers</p>
              <p style="margin:10px 0 0;font-size:11px;color:#a0aeb8;">© ${year} ${brand}</p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}

export function buildInvoiceEmailText(p: InvoiceEmailParams) {
  const brand = env.APP_NAME || "Safar Libya";
  const firstName = p.guestName.trim().split(/\s+/)[0] || p.guestName;
  return [
    `مرحباً ${firstName}،`,
    ``,
    `شكراً لثقتك بـ${brand}. هذه فاتورة حجزك:`,
    `رقم الفاتورة: ${p.invoiceNumber}`,
    `الإقامة: ${p.propertyTitle}${p.cityName ? ` — ${p.cityName}` : ""}`,
    `الدخول: ${formatDateAr(p.checkIn)}`,
    `المغادرة: ${formatDateAr(p.checkOut)}`,
    `المدة: ${p.nights} ليالٍ · ${p.guests} ضيوف`,
    `الضيف: ${p.guestName}${p.guestPhone ? ` · ${p.guestPhone}` : ""}`,
    `المبلغ المدفوع: ${formatMoneyPlain(p.totalLyd, "LYD")} (من أصل ${formatMoneyPlain(p.totalTnd, "TND")})`,
    `سعر الصرف: 1 TND = ${p.exchangeRate} LYD`,
    ``,
    `نتمنى لك إقامة مريحة ورحلة سعيدة.`,
    p.dashboardUrl ? `لوحة التحكم: ${p.dashboardUrl}` : "",
    ``,
    `${brand} — Trusted Tunisia stays for Libyan travelers`,
  ]
    .filter(Boolean)
    .join("\n");
}

