// Contains the email template for user sign in via magic links. A user will be asked to
// click a verification email to sign in to the app, should they choose to sign in with magic
// links

import { createTransport } from "nodemailer";

export async function MagicLinksEmail({
  identifier,
  url,
  provider,
}: {
  identifier: string;
  url: string;
  provider: { server: any; from: string };
}) {
  const parsed = new URL(url);
  const host = parsed.host;

  const baseUrl = parsed.origin;
  const logoUrl = `${baseUrl}/domna-email-logo.png`;

  const token = parsed.searchParams.get("token");
  const email = parsed.searchParams.get("email");

  if (!token || !email) {
    throw new Error("Magic link token or email missing");
  }

  // Create a clean login link instead of the NextAuth callback
  const loginUrl = `${parsed.origin}/verify/${token}`;

  const transport = createTransport(provider.server);

  const brandColor = "#14163d"; // brand blue
  const accentColor = "#2d348f"; // deep blue
  const brown = "#c4a47c"; // brand brown
  const background = "#F9F9F9";

  const result = await transport.sendMail({
    to: identifier,
    from: provider.from,
    subject: "Sign in to Ara",
    text: plainText({ url: loginUrl, host }),
    html: domnaHtml({
      url: loginUrl,
      logoUrl,
      host,
      brandColor,
      accentColor,
      brown,
      background,
    }),
    headers: {
      "List-Unsubscribe": `<mailto:${provider.from}>`,
    },
  });

  const failed = result.rejected.filter(Boolean);
  if (failed.length) {
    throw new Error(`Email(s) (${failed.join(", ")}) could not be sent`);
  }
}

function domnaHtml({
  url,
  logoUrl,
  host,
  brandColor,
  accentColor,
  brown,
  background,
}: {
  url: string;
  logoUrl: string;
  host: string;
  brandColor: string;
  accentColor: string;
  brown: string;
  background: string;
}) {
  const escapedHost = host.replace(/\./g, "&#8203;.");

  return `
  <body style="background: ${background}; font-family: Helvetica, Arial, sans-serif; margin: 0; padding: 0;">
    <table width="100%" border="0" cellspacing="0" cellpadding="0" 
      style="max-width: 600px; margin: 40px auto; background: #fff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
      <tr>
        <td align="center" style="background: linear-gradient(90deg, ${brandColor}, ${accentColor}); padding: 12px 8px;">
          <img 
            src="${logoUrl}"
            alt="Domna Logo"
            width="120"
            height="auto"
            style="margin-bottom: 4px;"
          />
        </td>
      </tr>
      <tr>
        <td align="center" style="padding: 10px 10px 10px; color: #333;">
          <h2 style="color: ${brandColor}; font-size: 22px; margin-bottom: 16px;">Welcome back to Ara by Domna</h2>
          <p style="font-size: 16px; line-height: 1.6; color: #444; margin-bottom: 32px;">
            Click below to securely sign in to your account and continue your retrofit journey.
          </p>
          <a href="${url}" target="_blank" 
            style="display: inline-block; padding: 14px 28px; background: ${brown}; color: #fff; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 16px;">
            Sign in to Ara
          </a>
          <p style="margin-top: 36px; font-size: 13px; color: #777;">
            If you didn’t request this email, you can safely ignore it.
          </p>
        </td>
      </tr>
      <tr>
        <td align="center" style="padding: 20px; font-size: 12px; color: #999; border-top: 1px solid #eee;">
          &copy; ${new Date().getFullYear()} Domna Homes • <span style="color: ${accentColor};">${escapedHost}</span>
        </td>
      </tr>
    </table>
  </body>
  `;
}

function plainText({ url, host }: { url: string; host: string }) {
  return `Sign in to Ara by Domna\n${url}\n\nIf you did not request this email, you can safely ignore it.\n`;
}
