import { getTranslations } from "next-intl/server";
import { sendMail } from "@/lib/mail";
import { emailShell } from "@/lib/emailTemplate";
import { formatEUR } from "@/lib/orderConstants";
import type { OrderTag } from "@/lib/orderConstants";

// Alle vier Benachrichtigungen unten folgen demselben Muster wie die
// bestehenden Verifizierungs-/Reset-Mails (emailShell + sendMail), damit sie
// optisch zur Marke passen. Bewusst nie mit Order-Freitext bombardieren —
// nur die konkrete Änderung + Link zum Auftrag, Details liest man dort.
// Fehler beim Mailversand dürfen die eigentliche Aktion nie blockieren
// (Preis/Status/Ablehnung sind schon gespeichert) — daher wird hier nie
// geworfen, nur geloggt; siehe googleCalendar.ts für dasselbe Prinzip.

type NotifyClient = { email: string; name: string; locale: "de" | "en" };
type NotifyOrder = { id: string; characterOrConcept: string };

function orderUrl(locale: string, orderId: string) {
  return `${process.env.SITE_URL}/${locale}/account/orders/${orderId}`;
}

async function safeSend(fn: () => Promise<void>) {
  try {
    await fn();
  } catch (err) {
    console.error("Auftrags-Benachrichtigung fehlgeschlagen:", err);
  }
}

export function notifyClientPriceProposed(client: NotifyClient, order: NotifyOrder, amount: number) {
  return safeSend(async () => {
    const isEn = client.locale === "en";
    const html = await emailShell({
      heading: `Hi ${client.name},`,
      bodyHtml: isEn
        ? `<p style="margin:0;">You've received a new price proposal for your order „<strong>${order.characterOrConcept}</strong>": <strong>${formatEUR(amount)}</strong>. You can accept it, decline it, or send a counter-offer in your account.</p>`
        : `<p style="margin:0;">Du hast einen neuen Preisvorschlag für deinen Auftrag „<strong>${order.characterOrConcept}</strong>" erhalten: <strong>${formatEUR(amount)}</strong>. Du kannst ihn in deinem Konto annehmen, ablehnen oder einen Gegenvorschlag machen.</p>`,
      buttonLabel: isEn ? "View order" : "Auftrag ansehen",
      buttonUrl: orderUrl(client.locale, order.id),
      footerNote: isEn
        ? "You're receiving this because you have an open order with Rakku Photography."
        : "Du erhältst diese E-Mail, weil du einen offenen Auftrag bei Rakku Photography hast.",
    });
    await sendMail(
      client.email,
      isEn ? "New price proposal — Rakku Photography" : "Neuer Preisvorschlag — Rakku Photography",
      html
    );
  });
}

export function notifyClientPriceResponded(client: NotifyClient, order: NotifyOrder, decision: "accepted" | "rejected") {
  return safeSend(async () => {
    const isEn = client.locale === "en";
    const accepted = decision === "accepted";
    const html = await emailShell({
      heading: `Hi ${client.name},`,
      bodyHtml: isEn
        ? `<p style="margin:0;">Your counter-offer for „<strong>${order.characterOrConcept}</strong>" has been <strong>${accepted ? "accepted" : "declined"}</strong>.${accepted ? "" : " You're welcome to send a new offer."}</p>`
        : `<p style="margin:0;">Dein Gegenvorschlag für „<strong>${order.characterOrConcept}</strong>" wurde <strong>${accepted ? "angenommen" : "abgelehnt"}</strong>.${accepted ? "" : " Du kannst gerne einen neuen Vorschlag machen."}</p>`,
      buttonLabel: isEn ? "View order" : "Auftrag ansehen",
      buttonUrl: orderUrl(client.locale, order.id),
      footerNote: isEn
        ? "You're receiving this because you have an open order with Rakku Photography."
        : "Du erhältst diese E-Mail, weil du einen offenen Auftrag bei Rakku Photography hast.",
    });
    await sendMail(
      client.email,
      isEn
        ? `Price proposal ${accepted ? "accepted" : "declined"} — Rakku Photography`
        : `Preisvorschlag ${accepted ? "angenommen" : "abgelehnt"} — Rakku Photography`,
      html
    );
  });
}

// Manuell vom Team ausgelöst (Button im Auftrag, siehe AdminContractPanel +
// sendContractReminderAction) - bewusst nicht automatisch/per Cron, mit
// Cooldown gegen versehentliches Zuspammen (siehe REMINDER_COOLDOWN_HOURS).
export function notifyClientContractReminder(client: NotifyClient, order: NotifyOrder) {
  return safeSend(async () => {
    const isEn = client.locale === "en";
    const html = await emailShell({
      heading: `Hi ${client.name},`,
      bodyHtml: isEn
        ? `<p style="margin:0;">Just a friendly reminder — the contract for your order „<strong>${order.characterOrConcept}</strong>" is still waiting for your signature. You can sign it directly in your account.</p>`
        : `<p style="margin:0;">Kurze Erinnerung — der Vertrag für deinen Auftrag „<strong>${order.characterOrConcept}</strong>" wartet noch auf deine Unterschrift. Du kannst ihn direkt in deinem Konto unterschreiben.</p>`,
      buttonLabel: isEn ? "Sign contract" : "Vertrag unterschreiben",
      buttonUrl: orderUrl(client.locale, order.id),
      footerNote: isEn
        ? "You're receiving this because you have an open order with Rakku Photography."
        : "Du erhältst diese E-Mail, weil du einen offenen Auftrag bei Rakku Photography hast.",
    });
    await sendMail(
      client.email,
      isEn ? "Reminder: contract awaiting signature — Rakku Photography" : "Erinnerung: Vertrag wartet auf Unterschrift — Rakku Photography",
      html
    );
  });
}

export async function notifyClientStatusChanged(client: NotifyClient, order: NotifyOrder, tag: OrderTag) {
  return safeSend(async () => {
    const isEn = client.locale === "en";
    const t = await getTranslations({ locale: client.locale, namespace: "orders" });
    const tagLabel = t(`orderTags.${tag}`);
    const html = await emailShell({
      heading: `Hi ${client.name},`,
      bodyHtml: isEn
        ? `<p style="margin:0;">The status of your order „<strong>${order.characterOrConcept}</strong>" has changed to: <strong>${tagLabel}</strong>.</p>`
        : `<p style="margin:0;">Der Status deines Auftrags „<strong>${order.characterOrConcept}</strong>" hat sich geändert zu: <strong>${tagLabel}</strong>.</p>`,
      buttonLabel: isEn ? "View order" : "Auftrag ansehen",
      buttonUrl: orderUrl(client.locale, order.id),
      footerNote: isEn
        ? "You're receiving this because you have an open order with Rakku Photography."
        : "Du erhältst diese E-Mail, weil du einen offenen Auftrag bei Rakku Photography hast.",
    });
    await sendMail(
      client.email,
      isEn ? "Order status updated — Rakku Photography" : "Auftragsstatus aktualisiert — Rakku Photography",
      html
    );
  });
}

export function notifyClientOrderRejected(client: NotifyClient, order: NotifyOrder, reasonLabel: string, note: string) {
  return safeSend(async () => {
    const isEn = client.locale === "en";
    const html = await emailShell({
      heading: `Hi ${client.name},`,
      bodyHtml: isEn
        ? `<p style="margin:0;">Unfortunately I have to decline your order „<strong>${order.characterOrConcept}</strong>".</p><p style="margin:12px 0 0;">${reasonLabel}${note ? ` ${note}` : ""}</p>`
        : `<p style="margin:0;">Leider muss ich deinen Auftrag „<strong>${order.characterOrConcept}</strong>" ablehnen.</p><p style="margin:12px 0 0;">${reasonLabel}${note ? ` ${note}` : ""}</p>`,
      buttonLabel: isEn ? "View order" : "Auftrag ansehen",
      buttonUrl: orderUrl(client.locale, order.id),
      footerNote: isEn
        ? "If you have any questions, just reply to this email."
        : "Bei Fragen antworte gerne einfach auf diese E-Mail.",
    });
    await sendMail(
      client.email,
      isEn ? "Your order was declined — Rakku Photography" : "Dein Auftrag wurde abgelehnt — Rakku Photography",
      html
    );
  });
}

const REMINDER_LEVEL_TITLES_DE: Record<number, string> = { 1: "Zahlungserinnerung", 2: "1. Mahnung" };
const REMINDER_LEVEL_TITLES_EN: Record<number, string> = { 1: "payment reminder", 2: "1st reminder notice" };
function reminderLevelTitle(level: number, isEn: boolean) {
  if (isEn) return REMINDER_LEVEL_TITLES_EN[level] || `${level - 1}. reminder notice`;
  return REMINDER_LEVEL_TITLES_DE[level] || `${level - 1}. Mahnung`;
}

export function notifyClientReminderSent(
  client: NotifyClient,
  order: NotifyOrder,
  level: number,
  amountDue: number,
  fee: number,
  dueDate: Date
) {
  return safeSend(async () => {
    const isEn = client.locale === "en";
    const levelTitle = reminderLevelTitle(level, isEn);
    const dueDateStr = dueDate.toLocaleDateString(isEn ? "en-GB" : "de-DE");
    const feeNote =
      fee > 0
        ? isEn
          ? `<p style="margin:12px 0 0;">This includes a ${formatEUR(fee)} reminder fee for this stage.</p>`
          : `<p style="margin:12px 0 0;">Darin enthalten ist eine Mahngebühr von ${formatEUR(fee)} für diese Stufe.</p>`
        : "";
    const html = await emailShell({
      heading: `Hi ${client.name},`,
      bodyHtml: isEn
        ? `<p style="margin:0;">This is a friendly ${levelTitle} regarding your order „<strong>${order.characterOrConcept}</strong>" — we haven't received your payment of <strong>${formatEUR(amountDue)}</strong> yet. Please transfer it by <strong>${dueDateStr}</strong>.</p>${feeNote}`
        : `<p style="margin:0;">Dies ist eine ${levelTitle} zu deinem Auftrag „<strong>${order.characterOrConcept}</strong>" — für die zugehörige Rechnung konnten wir bislang leider keinen Zahlungseingang feststellen. Bitte überweise <strong>${formatEUR(amountDue)}</strong> bis zum <strong>${dueDateStr}</strong>.</p>${feeNote}`,
      buttonLabel: isEn ? "View order & details" : "Auftrag & Details ansehen",
      buttonUrl: orderUrl(client.locale, order.id),
      footerNote: isEn
        ? "Already paid? Please disregard this email — payments can take a few days to process."
        : "Schon bezahlt? Dann bitte diese E-Mail ignorieren — Überweisungen brauchen manchmal ein paar Tage.",
    });
    await sendMail(
      client.email,
      isEn ? `Payment reminder — Rakku Photography` : `${levelTitle} — Rakku Photography`,
      html
    );
  });
}

export function notifyClientFeedbackRequest(client: NotifyClient, order: NotifyOrder, token: string) {
  return safeSend(async () => {
    const isEn = client.locale === "en";
    const feedbackUrl = `${process.env.SITE_URL}/${client.locale}/feedback/${token}`;
    const html = await emailShell({
      heading: `Hi ${client.name},`,
      bodyHtml: isEn
        ? `<p style="margin:0;">Your order „<strong>${order.characterOrConcept}</strong>" is wrapped up — I hope you love the results! I'd love to hear how it went, it only takes a minute and helps me keep improving.</p>`
        : `<p style="margin:0;">Dein Auftrag „<strong>${order.characterOrConcept}</strong>" ist abgeschlossen — ich hoffe, die Ergebnisse gefallen dir! Ich würde mich sehr über eine kurze Rückmeldung freuen, dauert nur eine Minute und hilft mir, mich weiter zu verbessern.</p>`,
      buttonLabel: isEn ? "Give feedback" : "Feedback geben",
      buttonUrl: feedbackUrl,
      footerNote: isEn
        ? "You're receiving this because your order was just marked as completed."
        : "Du erhältst diese E-Mail, weil dein Auftrag gerade als abgeschlossen markiert wurde.",
    });
    await sendMail(
      client.email,
      isEn ? "How did it go? — Rakku Photography" : "Wie war's? — Rakku Photography",
      html
    );
  });
}
