import { Document, Page, Text, View, StyleSheet, renderToBuffer } from "@react-pdf/renderer";
import type { ReminderDoc } from "@/models/Reminder";
import type { InvoiceDoc } from "@/models/Invoice";
import { formatAddress, formatEUR, formatDateDE } from "@/lib/orderConstants";

const styles = StyleSheet.create({
  page: { padding: 42, paddingBottom: 60, fontSize: 10, fontFamily: "Helvetica", color: "#1a1a1a" },
  title: { fontSize: 18, fontFamily: "Helvetica-Bold", marginBottom: 4 },
  subtitle: { fontSize: 10, color: "#555", marginBottom: 24 },
  row: { flexDirection: "row", marginBottom: 3 },
  label: { width: 140, color: "#555" },
  value: { flex: 1 },
  p: { marginBottom: 6, lineHeight: 1.5 },
  totalsRow: { flexDirection: "row", justifyContent: "flex-end", marginTop: 10 },
  totalsLabel: { width: 110, textAlign: "right", color: "#555" },
  totalsValue: { width: 90, textAlign: "right" },
  // "fixed" hält die Fußzeile auf jeder Seite fest unten, unabhängig vom
  // normalen Textfluss — siehe ausführlicher Kommentar in documentPdf.tsx.
  footerMeta: {
    position: "absolute",
    bottom: 20,
    left: 42,
    right: 42,
    fontSize: 8,
    color: "#999",
    textAlign: "center",
    borderTop: "1px solid #eee",
    paddingTop: 6,
    flexDirection: "row",
    justifyContent: "space-between",
  },
});

function Field({ label, value }: { label: string; value?: string }) {
  if (!value) return null;
  return (
    <View style={styles.row}>
      <Text style={styles.label}>{label}</Text>
      <Text style={styles.value}>{value}</Text>
    </View>
  );
}

const fmt = formatEUR;

const LEVEL_TITLES: Record<number, string> = {
  1: "Zahlungserinnerung",
  2: "1. Mahnung",
};

function levelTitle(level: number) {
  return LEVEL_TITLES[level] || `${level - 1}. Mahnung`;
}

function ReminderPage({ reminder, invoice }: { reminder: ReminderDoc; invoice: InvoiceDoc }) {
  return (
    <Page size="A4" style={styles.page}>
      <View style={{ flexDirection: "row", justifyContent: "space-between", marginBottom: 28 }}>
        <View>
          <Text style={{ fontFamily: "Helvetica-Bold", marginBottom: 2 }}>{invoice.businessName}</Text>
          {invoice.businessLegalName && invoice.businessLegalName !== invoice.businessName && (
            <Text style={{ color: "#555", marginBottom: 2 }}>{invoice.businessLegalName}</Text>
          )}
          <Text style={{ color: "#555" }}>
            {formatAddress({
              street: invoice.businessStreet,
              postCode: invoice.businessPostCode,
              city: invoice.businessCity,
              countryCode: invoice.businessCountryCode,
            })}
          </Text>
        </View>
        <View>
          <Text style={{ fontFamily: "Helvetica-Bold", marginBottom: 2 }}>{invoice.clientName}</Text>
          <Text style={{ color: "#555" }}>
            {formatAddress({
              street: invoice.clientStreet,
              postCode: invoice.clientPostCode,
              city: invoice.clientCity,
              countryCode: invoice.clientCountryCode,
            })}
          </Text>
        </View>
      </View>

      <Text style={styles.title}>{levelTitle(reminder.level)}</Text>
      <Text style={styles.subtitle}>zu Rechnung {invoice.number}</Text>

      <Field label="Datum" value={formatDateDE(new Date(reminder.createdAt))} />
      <Field label="Rechnungsnummer" value={invoice.number} />
      <Field label="Rechnungsdatum" value={formatDateDE(new Date(invoice.issueDate))} />
      <Field label="Verwendungszweck" value={invoice.paymentReference} />

      <Text style={{ ...styles.p, marginTop: 20 }}>
        für die oben genannte Rechnung konnten wir bislang leider keinen Zahlungseingang feststellen. Wir bitten Sie,
        den offenen Betrag bis zum {formatDateDE(new Date(reminder.dueDate))} auf folgendes Konto zu
        überweisen:
      </Text>

      <Field label="Empfänger" value={invoice.accountHolderName || invoice.businessName} />
      <Field label="IBAN" value={invoice.businessIban} />
      <Field label="BIC" value={invoice.businessBic} />
      <Field label="Bank" value={invoice.businessBankName} />
      <Field label="Verwendungszweck" value={invoice.paymentReference} />

      {reminder.fee > 0 && (
        <>
          <View style={styles.totalsRow}>
            <Text style={styles.totalsLabel}>Rechnungsbetrag</Text>
            <Text style={styles.totalsValue}>{fmt(reminder.amountDue - reminder.fee)}</Text>
          </View>
          <View style={styles.totalsRow}>
            <Text style={styles.totalsLabel}>Mahngebühr (diese Stufe)</Text>
            <Text style={styles.totalsValue}>{fmt(reminder.fee)}</Text>
          </View>
        </>
      )}
      <View style={styles.totalsRow}>
        <Text style={[styles.totalsLabel, { fontFamily: "Helvetica-Bold" }]}>Offener Betrag</Text>
        <Text style={[styles.totalsValue, { fontFamily: "Helvetica-Bold" }]}>{fmt(reminder.amountDue)}</Text>
      </View>

      {reminder.note && <Text style={{ ...styles.p, marginTop: 20 }}>{reminder.note}</Text>}

      <Text style={{ ...styles.p, marginTop: 24, fontSize: 8, color: "#777" }}>
        Sollten Sie den Betrag bereits beglichen haben, betrachten Sie dieses Schreiben als gegenstandslos.
      </Text>

      <View style={styles.footerMeta} fixed>
        <Text>
          {levelTitle(reminder.level)} zu Rechnung {invoice.number}
        </Text>
        <Text render={({ pageNumber, totalPages }) => `Seite ${pageNumber} von ${totalPages}`} />
      </View>
    </Page>
  );
}

export async function renderReminderPdf(reminder: ReminderDoc, invoice: InvoiceDoc): Promise<Buffer> {
  const doc = (
    <Document>
      <ReminderPage reminder={reminder} invoice={invoice} />
    </Document>
  );
  return renderToBuffer(doc);
}
