import nodemailer from "nodemailer";

const SMTP_HOST = process.env.SMTP_HOST;
const SMTP_PORT = Number(process.env.SMTP_PORT || "587");
const SMTP_USER = process.env.SMTP_USER;
const SMTP_PASS = process.env.SMTP_PASS;
const BROCHURE_MAIL_FROM = process.env.BROCHURE_MAIL_FROM;
const BROCHURE_SALES_NOTIFY_TO =
  process.env.BROCHURE_SALES_NOTIFY_TO;

const getTransporter = () => {
  if (
    !SMTP_HOST ||
    !SMTP_USER ||
    !SMTP_PASS ||
    !BROCHURE_MAIL_FROM ||
    !BROCHURE_SALES_NOTIFY_TO
  ) {
    throw new Error("Missing SMTP configuration for brochure email.");
  }

  const isImplicitTLS = SMTP_PORT === 465;

  return nodemailer.createTransport({
    host: SMTP_HOST,
    port: SMTP_PORT,
    secure: isImplicitTLS,
    requireTLS: !isImplicitTLS,
    auth: {
      user: SMTP_USER,
      pass: SMTP_PASS,
    },
    tls: {
      minVersion: "TLSv1.2",
    },
  });
};

/**
 * Sales-only notification: project name, address, type, and lead contact details.
 * No download links; sales sends the brochure as an attachment from their mail client.
 */
export const sendBrochureSalesNotification = async ({
  customerEmail,
  phone,
  propertyKey,
  propertyName,
  propertyAddress,
  propertyType,
}: {
  customerEmail: string;
  phone: string;
  propertyKey: string;
  propertyName: string;
  propertyAddress: string;
  propertyType?: string | null;
}) => {
  const transporter = getTransporter();
  const subject = `New Brochure Request — ${propertyName}`;
  const propertyTypeLabel = propertyType
    ? propertyType.charAt(0).toUpperCase() + propertyType.slice(1)
    : "Not specified";

  const requestedAt = new Date();
  const requestedAtLabel = requestedAt.toLocaleString("en-GB", {
    timeZone: "Asia/Dhaka",
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    hour12: true,
  });

  const text = [
    "NEW BROCHURE REQUEST",
    "",
    `Received: ${requestedAtLabel} (Asia/Dhaka)`,
    "",
    "PROPERTY DETAILS",
    `  Project:   ${propertyName}`,
    `  Type:      ${propertyTypeLabel}`,
    `  Location:  ${propertyAddress}`,
    `  Site key:  ${propertyKey}`,
    "",
    "CLIENT CONTACT",
    `  Email:     ${customerEmail}`,
    `  Phone:     ${phone}`,
    "",
    "Reply to the client from your mailbox and attach the brochure PDF.",
    "The website does not deliver the brochure directly.",
  ].join("\n");

  const replyMailto = `mailto:${customerEmail}?subject=${encodeURIComponent(
    `Your brochure for ${propertyName}`
  )}`;

  const html = buildSalesNotificationHtml({
    propertyName,
    propertyTypeLabel,
    propertyAddress,
    propertyKey,
    customerEmail,
    phone,
    requestedAtLabel,
    replyMailto,
  });

  await transporter.sendMail({
    from: BROCHURE_MAIL_FROM,
    to: BROCHURE_SALES_NOTIFY_TO,
    subject,
    text,
    html,
  });
};

function buildSalesNotificationHtml({
  propertyName,
  propertyTypeLabel,
  propertyAddress,
  propertyKey,
  customerEmail,
  phone,
  requestedAtLabel,
  replyMailto,
}: {
  propertyName: string;
  propertyTypeLabel: string;
  propertyAddress: string;
  propertyKey: string;
  customerEmail: string;
  phone: string;
  requestedAtLabel: string;
  replyMailto: string;
}) {
  const name = escapeHtml(propertyName);
  const type = escapeHtml(propertyTypeLabel);
  const address = escapeHtml(propertyAddress);
  const key = escapeHtml(propertyKey);
  const email = escapeHtml(customerEmail);
  const phoneE = escapeHtml(phone);
  const time = escapeHtml(requestedAtLabel);

  return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${name} — Brochure Request</title>
</head>
<body style="margin:0;padding:0;background-color:#f3f4f6;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#1f2937;">
<table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="background-color:#f3f4f6;">
  <tr>
    <td align="center" style="padding:32px 16px;">
      <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="600" style="max-width:600px;background-color:#ffffff;border-radius:8px;overflow:hidden;border:1px solid #e5e7eb;">

        <tr>
          <td style="background-color:#333333;padding:28px 32px;">
            <div style="color:#cd607f;font-size:11px;letter-spacing:2.5px;text-transform:uppercase;font-weight:700;">Navana Real Estate</div>
            <div style="margin-top:8px;color:#ffffff;font-size:22px;font-weight:600;line-height:1.3;">New Brochure Request</div>
            <div style="margin-top:6px;color:#a7a7a7;font-size:13px;">Received ${time} (Asia/Dhaka)</div>
          </td>
        </tr>

        <tr>
          <td style="padding:28px 32px 8px 32px;">
            <p style="margin:0 0 24px 0;color:#4b5563;font-size:14px;line-height:1.6;">
              A visitor submitted the brochure form on the website. Please reach out to the client and send the brochure PDF as an attachment from your mailbox.
            </p>

            <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="background-color:#fafafa;border-left:3px solid #cd607f;border-radius:4px;margin-bottom:16px;">
              <tr>
                <td style="padding:18px 22px;">
                  <div style="margin-bottom:14px;color:#6b7280;font-size:11px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;">Property Details</div>
                  <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
                    <tr>
                      <td style="padding:5px 0;color:#6b7280;font-size:13px;width:110px;vertical-align:top;">Project</td>
                      <td style="padding:5px 0;color:#111827;font-size:14px;font-weight:600;">${name}</td>
                    </tr>
                    <tr>
                      <td style="padding:5px 0;color:#6b7280;font-size:13px;vertical-align:top;">Type</td>
                      <td style="padding:5px 0;color:#111827;font-size:14px;">${type}</td>
                    </tr>
                    <tr>
                      <td style="padding:5px 0;color:#6b7280;font-size:13px;vertical-align:top;">Location</td>
                      <td style="padding:5px 0;color:#111827;font-size:14px;line-height:1.5;">${address}</td>
                    </tr>
                    <tr>
                      <td style="padding:5px 0;color:#6b7280;font-size:13px;vertical-align:top;">Site key</td>
                      <td style="padding:5px 0;color:#6b7280;font-size:12px;font-family:'SFMono-Regular',Consolas,'Liberation Mono',Menlo,monospace;">${key}</td>
                    </tr>
                  </table>
                </td>
              </tr>
            </table>

            <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="background-color:#fafafa;border-left:3px solid #333333;border-radius:4px;margin-bottom:24px;">
              <tr>
                <td style="padding:18px 22px;">
                  <div style="margin-bottom:14px;color:#6b7280;font-size:11px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;">Client Contact</div>
                  <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
                    <tr>
                      <td style="padding:5px 0;color:#6b7280;font-size:13px;width:110px;vertical-align:top;">Email</td>
                      <td style="padding:5px 0;">
                        <a href="mailto:${email}" style="color:#cd607f;font-size:14px;font-weight:600;text-decoration:none;">${email}</a>
                      </td>
                    </tr>
                    <tr>
                      <td style="padding:5px 0;color:#6b7280;font-size:13px;vertical-align:top;">Phone</td>
                      <td style="padding:5px 0;">
                        <a href="tel:${phoneE}" style="color:#cd607f;font-size:14px;font-weight:600;text-decoration:none;">${phoneE}</a>
                      </td>
                    </tr>
                  </table>
                </td>
              </tr>
            </table>

            <table role="presentation" cellspacing="0" cellpadding="0" border="0">
              <tr>
                <td style="border-radius:4px;background-color:#cd607f;">
                  <a href="${replyMailto}" style="display:inline-block;padding:12px 26px;color:#ffffff;font-size:14px;font-weight:600;text-decoration:none;letter-spacing:0.3px;">Reply to Client</a>
                </td>
              </tr>
            </table>

            <p style="margin:20px 0 0 0;color:#9ca3af;font-size:12px;line-height:1.6;">
              Tip: open this email on your work mailbox, click <em>Reply to Client</em>, attach the brochure PDF, and send. The website itself does not deliver the brochure.
            </p>
          </td>
        </tr>

        <tr>
          <td style="background-color:#fafafa;padding:18px 32px;border-top:1px solid #e5e7eb;">
            <p style="margin:0;color:#9ca3af;font-size:11px;line-height:1.6;text-align:center;">
              Sent automatically from the brochure form on
              <a href="https://navana-realestate.com" style="color:#6b7280;text-decoration:underline;">navana-realestate.com</a>.
              Do not reply to this address — use the <em>Reply to Client</em> button above to contact the lead directly.
            </p>
          </td>
        </tr>

      </table>
    </td>
  </tr>
</table>
</body>
</html>`;
}

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