import nodemailer from "nodemailer";

function getTransport() {
  const host = process.env["SMTP_HOST"];
  if (!host) return null;

  return nodemailer.createTransport({
    host,
    port: parseInt(process.env["SMTP_PORT"] ?? "587"),
    secure: process.env["SMTP_SECURE"] === "true",
    auth: {
      user: process.env["SMTP_USER"],
      pass: process.env["SMTP_PASS"],
    },
  });
}

const FROM = process.env["SMTP_FROM"] ?? "Epicure <noreply@epicure.app>";

export async function sendEmail({
  to,
  subject,
  html,
}: {
  to: string;
  subject: string;
  html: string;
}) {
  const transport = getTransport();
  if (!transport) {
    console.log(`[email:dev] No SMTP_HOST — logging email instead.\n  Subject: ${subject}\n  To: ${to}\n  Body: ${html.replace(/<[^>]+>/g, "").slice(0, 200)}`);
    return;
  }
  try {
    const info = await transport.sendMail({ from: FROM, to, subject, html });
    console.log(`[email:sent] "${subject}" → ${to} | id:${info.messageId} | response:${info.response}`);
  } catch (err) {
    console.error(`[email:error] "${subject}" → ${to} |`, err);
    throw err;
  }
}

// ── Templates ─────────────────────────────────────────────────────────────────

function layout(title: string, body: string) {
  return `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>${title}</title>
</head>
<body style="margin:0;padding:0;background:#fafaf9;font-family:Georgia,serif;color:#1c1917;">
  <table width="100%" cellpadding="0" cellspacing="0" style="padding:40px 20px;">
    <tr><td align="center">
      <table width="560" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:12px;overflow:hidden;border:1px solid #e7e5e4;">
        <tr><td style="padding:32px 40px;border-bottom:1px solid #e7e5e4;">
          <span style="font-size:22px;font-weight:bold;letter-spacing:-0.5px;">🍴 Epicure</span>
        </td></tr>
        <tr><td style="padding:40px;">
          ${body}
        </td></tr>
        <tr><td style="padding:24px 40px;background:#fafaf9;border-top:1px solid #e7e5e4;">
          <p style="margin:0;font-size:12px;color:#78716c;">You received this email from Epicure. If you didn't request it, ignore this email.</p>
        </td></tr>
      </table>
    </td></tr>
  </table>
</body>
</html>`;
}

function btn(href: string, label: string) {
  return `<a href="${href}" style="display:inline-block;background:#1c1917;color:#fff;padding:12px 24px;border-radius:8px;text-decoration:none;font-size:15px;font-weight:600;margin:24px 0;">${label}</a>`;
}

export function verifyEmailHtml(url: string) {
  return layout(
    "Verify your email — Epicure",
    `<h1 style="margin:0 0 8px;font-size:24px;">Verify your email</h1>
     <p style="margin:0 0 4px;color:#57534e;line-height:1.6;">Click the button below to verify your email address and activate your Epicure account.</p>
     ${btn(url, "Verify email")}
     <p style="margin:16px 0 0;font-size:13px;color:#a8a29e;">Link expires in 24 hours. Or paste this URL into your browser:<br/>
     <a href="${url}" style="color:#78716c;font-size:12px;word-break:break-all;">${url}</a></p>`
  );
}

export function resetPasswordHtml(url: string) {
  return layout(
    "Reset your password — Epicure",
    `<h1 style="margin:0 0 8px;font-size:24px;">Reset your password</h1>
     <p style="margin:0 0 4px;color:#57534e;line-height:1.6;">We received a request to reset the password for your Epicure account.</p>
     ${btn(url, "Reset password")}
     <p style="margin:16px 0 0;font-size:13px;color:#a8a29e;">Link expires in 1 hour. If you didn't request a reset, you can safely ignore this email.</p>`
  );
}

export function notificationEmailHtml(title: string, body: string, url: string) {
  return layout(
    `${title} — Epicure`,
    `<h1 style="margin:0 0 8px;font-size:24px;">${title}</h1>
     <p style="margin:0 0 4px;color:#57534e;line-height:1.6;">${body}</p>
     ${btn(url, "View on Epicure")}`
  );
}

export function weeklyDigestHtml(opts: {
  newFollowers: number;
  newComments: number;
  newRatings: number;
  trending: { id: string; title: string }[];
  baseUrl: string;
}) {
  const { newFollowers, newComments, newRatings, trending, baseUrl } = opts;

  const stats = [
    newFollowers > 0 ? `<strong>${newFollowers}</strong> new follower${newFollowers === 1 ? "" : "s"}` : null,
    newComments > 0 ? `<strong>${newComments}</strong> new comment${newComments === 1 ? "" : "s"} on your recipes` : null,
    newRatings > 0 ? `<strong>${newRatings}</strong> new rating${newRatings === 1 ? "" : "s"} on your recipes` : null,
  ].filter((s): s is string => s !== null);

  const statsHtml = stats.length > 0
    ? `<ul style="margin:0 0 24px;padding:0 0 0 20px;color:#57534e;line-height:1.8;">
        ${stats.map((s) => `<li>${s}</li>`).join("")}
       </ul>`
    : `<p style="margin:0 0 24px;color:#57534e;line-height:1.6;">Quiet week on your recipes — but here's what's trending.</p>`;

  const trendingHtml = trending.length > 0
    ? `<h2 style="margin:0 0 8px;font-size:16px;">Trending this week</h2>
       <ol style="margin:0 0 8px;padding:0 0 0 20px;color:#57534e;line-height:1.8;">
         ${trending.map((r) => `<li><a href="${baseUrl}/recipes/${r.id}" style="color:#1c1917;">${r.title}</a></li>`).join("")}
       </ol>`
    : "";

  return layout(
    "Your weekly digest — Epicure",
    `<h1 style="margin:0 0 8px;font-size:24px;">Your week on Epicure</h1>
     ${statsHtml}
     ${trendingHtml}
     ${btn(baseUrl, "Open Epicure")}`
  );
}

export function supportTicketReceivedHtml(opts: {
  type: string;
  title: string;
  ticketUrl: string;
  giteaIssueUrl: string | null;
}) {
  const { type, title, ticketUrl, giteaIssueUrl } = opts;
  const typeLabel = type === "bug" ? "bug report" : type === "suggestion" ? "suggestion" : "question";
  return layout(
    "We got your message — Epicure",
    `<h1 style="margin:0 0 8px;font-size:24px;">Thanks for reaching out</h1>
     <p style="margin:0 0 4px;color:#57534e;line-height:1.6;">We received your ${typeLabel}:</p>
     <p style="margin:16px 0;padding:12px 16px;background:#fafaf9;border-radius:8px;border:1px solid #e7e5e4;font-weight:600;">${title}</p>
     <p style="margin:0 0 4px;color:#57534e;line-height:1.6;">We'll follow up if we need more details.${giteaIssueUrl ? " It's also been logged for tracking." : ""}</p>
     ${btn(ticketUrl, "View your ticket")}`
  );
}

export function welcomeHtml(name: string) {
  return layout(
    "Welcome to Epicure",
    `<h1 style="margin:0 0 8px;font-size:24px;">Welcome, ${name}!</h1>
     <p style="margin:0 0 16px;color:#57534e;line-height:1.6;">Your account is ready. Start by creating your first recipe, importing from a URL, or letting AI generate one for you.</p>
     ${btn(process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000", "Go to Epicure")}
     <p style="margin:16px 0 0;font-size:13px;color:#a8a29e;">Questions? Just reply to this email.</p>`
  );
}
