import { env } from "@kk/env/server";
import nodemailer from "nodemailer";

// Singleton transport — created once per module, reused across all email sends.
// Re-creating it on every call causes EventEmitter listener accumulation in
// long-lived Cloudflare Worker processes, triggering memory leak warnings.
let _transport: nodemailer.Transporter | null | undefined;

function getTransport(): nodemailer.Transporter | null {
	if (_transport !== undefined) return _transport;
	if (!env.SMTP_HOST || !env.SMTP_USER || !env.SMTP_PASS) {
		_transport = null;
		return null;
	}
	_transport = nodemailer.createTransport({
		host: env.SMTP_HOST,
		port: env.SMTP_PORT,
		secure: env.SMTP_PORT === 465,
		auth: {
			user: env.SMTP_USER,
			pass: env.SMTP_PASS,
		},
	});
	return _transport;
}

const from = env.SMTP_FROM ?? "Kunstenkamp <info@kunstenkamp.be>";
const baseUrl = env.BETTER_AUTH_URL ?? "https://kunstenkamp.be";

function registrationConfirmationHtml(params: {
	firstName: string;
	manageUrl: string;
	wantsToPerform: boolean;
	artForm?: string | null;
	giftAmount?: number;
	drinkCardValue?: number;
}) {
	const role = params.wantsToPerform
		? `Optreden${params.artForm ? ` — ${params.artForm}` : ""}`
		: "Toeschouwer";

	const giftCents = params.giftAmount ?? 0;
	// drinkCardValue is stored in euros (e.g., 5), giftAmount in cents (e.g., 5000)
	const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
	const hasPayment = drinkCardCents > 0 || giftCents > 0;

	const formatEuro = (cents: number) =>
		`€${(cents / 100).toFixed(cents % 100 === 0 ? 0 : 2).replace(".", ",")}`;

	const paymentSummary = hasPayment
		? `<table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:16px 0;">
				<tr>
					<td style="padding:20px 24px;">
						<p style="margin:0 0 12px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">Betaling</p>
						${drinkCardCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.5;">Drinkkaart: <span style="color:#ffffff;font-weight:500;">${formatEuro(drinkCardCents)}</span></p>` : ""}
						${giftCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.5;">Vrijwillige gift: <span style="color:#ffffff;font-weight:500;">${formatEuro(giftCents)}</span></p>` : ""}
						<p style="margin:16px 0 0;padding-top:12px;border-top:1px solid rgba(255,255,255,0.1);font-size:18px;color:#ffffff;font-weight:600;">Totaal: ${formatEuro(drinkCardCents + giftCents)}</p>
					</td>
				</tr>
			</table>`
		: "";

	return `<!DOCTYPE html>
<html lang="nl">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Bevestiging inschrijving</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background:#214e51;border-radius:4px;overflow:hidden;">
          <!-- Header -->
          <tr>
            <td style="padding:40px 48px 32px;">
              <p style="margin:0;font-size:13px;color:rgba(255,255,255,0.5);letter-spacing:0.08em;text-transform:uppercase;">Kunstenkamp</p>
              <h1 style="margin:12px 0 0;font-size:28px;color:#ffffff;font-weight:700;">Je inschrijving is bevestigd!</h1>
            </td>
          </tr>
          <!-- Body -->
          <tr>
            <td style="padding:0 48px 32px;">
              <p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
                Hoi ${params.firstName},
              </p>
              <p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
                We hebben je inschrijving voor <strong style="color:#ffffff;">Open Mic Night — vrijdag 24 april 2026</strong> in goede orde ontvangen.
              </p>
              <!-- Registration summary -->
              <table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:24px 0;">
                <tr>
                  <td style="padding:20px 24px;">
                    <p style="margin:0 0 8px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">Jouw rol</p>
                    <p style="margin:0;font-size:18px;color:#ffffff;font-weight:600;">${role}</p>
                  </td>
                </tr>
              </table>
              ${paymentSummary}
              <p style="margin:0 0 24px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
                Wil je je gegevens later nog aanpassen of je inschrijving annuleren? Gebruik dan de knop hieronder. De link is uniek voor jou — deel hem niet.
              </p>
              <!-- CTA button -->
              <table cellpadding="0" cellspacing="0">
                <tr>
                  <td style="border-radius:2px;background:#ffffff;">
                    <a href="${params.manageUrl}" style="display:inline-block;padding:14px 32px;font-size:16px;font-weight:600;color:#214e51;text-decoration:none;">
                      Beheer mijn inschrijving
                    </a>
                  </td>
                </tr>
              </table>
              <p style="margin:16px 0 0;font-size:13px;color:rgba(255,255,255,0.4);">
                Of kopieer deze link: <span style="color:rgba(255,255,255,0.6);">${params.manageUrl}</span>
              </p>
            </td>
          </tr>
          <!-- Footer -->
          <tr>
            <td style="padding:24px 48px;border-top:1px solid rgba(255,255,255,0.1);">
              <p style="margin:0;font-size:13px;color:rgba(255,255,255,0.4);line-height:1.6;">
                Vragen? Mail ons op <a href="mailto:info@kunstenkamp.be" style="color:rgba(255,255,255,0.6);">info@kunstenkamp.be</a><br/>
                Kunstenkamp vzw — Een initiatief voor en door kunstenaars.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}

function updateConfirmationHtml(params: {
	firstName: string;
	manageUrl: string;
	wantsToPerform: boolean;
	artForm?: string | null;
	giftAmount?: number;
	drinkCardValue?: number;
}) {
	const role = params.wantsToPerform
		? `Optreden${params.artForm ? ` — ${params.artForm}` : ""}`
		: "Toeschouwer";

	const giftCents = params.giftAmount ?? 0;
	// drinkCardValue is stored in euros (e.g., 5), giftAmount in cents (e.g., 5000)
	const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
	const hasPayment = drinkCardCents > 0 || giftCents > 0;

	const formatEuro = (cents: number) =>
		`€${(cents / 100).toFixed(cents % 100 === 0 ? 0 : 2).replace(".", ",")}`;

	const paymentSummary = hasPayment
		? `<table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:16px 0;">
				<tr>
					<td style="padding:20px 24px;">
						<p style="margin:0 0 12px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">Betaling</p>
						${drinkCardCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.5;">Drinkkaart: <span style="color:#ffffff;font-weight:500;">${formatEuro(drinkCardCents)}</span></p>` : ""}
						${giftCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.5;">Vrijwillige gift: <span style="color:#ffffff;font-weight:500;">${formatEuro(giftCents)}</span></p>` : ""}
						<p style="margin:16px 0 0;padding-top:12px;border-top:1px solid rgba(255,255,255,0.1);font-size:18px;color:#ffffff;font-weight:600;">Totaal: ${formatEuro(drinkCardCents + giftCents)}</p>
					</td>
				</tr>
			</table>`
		: "";

	return `<!DOCTYPE html>
<html lang="nl">
<head>
  <meta charset="UTF-8" />
  <title>Inschrijving bijgewerkt</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background:#214e51;border-radius:4px;overflow:hidden;">
          <tr>
            <td style="padding:40px 48px 32px;">
              <p style="margin:0;font-size:13px;color:rgba(255,255,255,0.5);letter-spacing:0.08em;text-transform:uppercase;">Kunstenkamp</p>
              <h1 style="margin:12px 0 0;font-size:28px;color:#ffffff;font-weight:700;">Inschrijving bijgewerkt</h1>
            </td>
          </tr>
          <tr>
            <td style="padding:0 48px 32px;">
              <p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
                Hoi ${params.firstName},
              </p>
              <p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
                Je inschrijving voor <strong style="color:#ffffff;">Open Mic Night — vrijdag 18 april 2026</strong> is succesvol bijgewerkt.
              </p>
              <table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:24px 0;">
                <tr>
                  <td style="padding:20px 24px;">
                    <p style="margin:0 0 8px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">Jouw rol</p>
                    <p style="margin:0;font-size:18px;color:#ffffff;font-weight:600;">${role}</p>
                  </td>
                </tr>
              </table>
              ${paymentSummary}
              <table cellpadding="0" cellspacing="0">
                <tr>
                  <td style="border-radius:2px;background:#ffffff;">
                    <a href="${params.manageUrl}" style="display:inline-block;padding:14px 32px;font-size:16px;font-weight:600;color:#214e51;text-decoration:none;">
                      Bekijk mijn inschrijving
                    </a>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          <tr>
            <td style="padding:24px 48px;border-top:1px solid rgba(255,255,255,0.1);">
              <p style="margin:0;font-size:13px;color:rgba(255,255,255,0.4);">
                Vragen? Mail ons op <a href="mailto:info@kunstenkamp.be" style="color:rgba(255,255,255,0.6);">info@kunstenkamp.be</a>
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}

function cancellationHtml(params: { firstName: string }) {
	return `<!DOCTYPE html>
<html lang="nl">
<head>
  <meta charset="UTF-8" />
  <title>Inschrijving geannuleerd</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background:#214e51;border-radius:4px;overflow:hidden;">
          <tr>
            <td style="padding:40px 48px 32px;">
              <p style="margin:0;font-size:13px;color:rgba(255,255,255,0.5);letter-spacing:0.08em;text-transform:uppercase;">Kunstenkamp</p>
              <h1 style="margin:12px 0 0;font-size:28px;color:#ffffff;font-weight:700;">Inschrijving geannuleerd</h1>
            </td>
          </tr>
          <tr>
            <td style="padding:0 48px 40px;">
              <p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
                Hoi ${params.firstName},
              </p>
              <p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
                Je inschrijving voor <strong style="color:#ffffff;">Open Mic Night — vrijdag 18 april 2026</strong> is geannuleerd.
              </p>
              <p style="margin:0;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">
                Van gedachten veranderd? Je kunt je altijd opnieuw inschrijven via <a href="${baseUrl}/#registration" style="color:#ffffff;">kunstenkamp.be</a>.
              </p>
            </td>
          </tr>
          <tr>
            <td style="padding:24px 48px;border-top:1px solid rgba(255,255,255,0.1);">
              <p style="margin:0;font-size:13px;color:rgba(255,255,255,0.4);">
                Vragen? Mail ons op <a href="mailto:info@kunstenkamp.be" style="color:rgba(255,255,255,0.6);">info@kunstenkamp.be</a>
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}

export async function sendConfirmationEmail(params: {
	to: string;
	firstName: string;
	managementToken: string;
	wantsToPerform: boolean;
	artForm?: string | null;
	giftAmount?: number;
	drinkCardValue?: number;
}) {
	const transport = getTransport();
	if (!transport) {
		console.warn("SMTP not configured — skipping confirmation email");
		return;
	}
	const manageUrl = `${baseUrl}/manage/${params.managementToken}`;
	await transport.sendMail({
		from,
		to: params.to,
		subject: "Bevestiging inschrijving — Open Mic Night",
		html: registrationConfirmationHtml({
			firstName: params.firstName,
			manageUrl,
			wantsToPerform: params.wantsToPerform,
			artForm: params.artForm,
			giftAmount: params.giftAmount,
			drinkCardValue: params.drinkCardValue,
		}),
	});
}

export async function sendUpdateEmail(params: {
	to: string;
	firstName: string;
	managementToken: string;
	wantsToPerform: boolean;
	artForm?: string | null;
	giftAmount?: number;
	drinkCardValue?: number;
}) {
	const transport = getTransport();
	if (!transport) {
		console.warn("SMTP not configured — skipping update email");
		return;
	}
	const manageUrl = `${baseUrl}/manage/${params.managementToken}`;
	await transport.sendMail({
		from,
		to: params.to,
		subject: "Inschrijving bijgewerkt — Open Mic Night",
		html: updateConfirmationHtml({
			firstName: params.firstName,
			manageUrl,
			wantsToPerform: params.wantsToPerform,
			artForm: params.artForm,
			giftAmount: params.giftAmount,
			drinkCardValue: params.drinkCardValue,
		}),
	});
}

export async function sendCancellationEmail(params: {
	to: string;
	firstName: string;
}) {
	const transport = getTransport();
	if (!transport) {
		console.warn("SMTP not configured — skipping cancellation email");
		return;
	}
	await transport.sendMail({
		from,
		to: params.to,
		subject: "Inschrijving geannuleerd — Open Mic Night",
		html: cancellationHtml({ firstName: params.firstName }),
	});
}
