import { jsPDF } from "jspdf";
import { autoTable } from "jspdf-autotable";

// ── Huisstijl ──────────────────────────────────────────────────
const GOUD: [number, number, number] = [201, 168, 76];
const BLAUW: [number, number, number] = [21, 101, 192];
const DONKER: [number, number, number] = [30, 30, 30];
const GRIJS: [number, number, number] = [110, 110, 110];

function euro(n: number): string {
  return "€ " + Math.round(n).toLocaleString("nl-BE");
}
function pct(n: number): string {
  return n.toFixed(2) + " %";
}

function finalY(doc: jsPDF): number {
  // jspdf-autotable schrijft de eindpositie naar lastAutoTable
  return (doc as unknown as { lastAutoTable?: { finalY: number } }).lastAutoTable?.finalY ?? 0;
}

function kop(doc: jsPDF, titel: string, badge: string): number {
  const M = 14;
  doc.setFont("helvetica", "bold");
  doc.setFontSize(7);
  doc.setTextColor(...GOUD);
  doc.text(badge.toUpperCase(), M, 16);

  doc.setFontSize(18);
  doc.setTextColor(...DONKER);
  doc.text(titel, M, 25);

  doc.setFont("helvetica", "normal");
  doc.setFontSize(8);
  doc.setTextColor(...GRIJS);
  doc.text("Notariskantoor te Tervuren", M, 31);

  doc.setDrawColor(...GOUD);
  doc.setLineWidth(0.5);
  doc.line(M, 34, 196, 34);
  return 42;
}

function voet(doc: jsPDF) {
  const h = doc.internal.pageSize.getHeight();
  const datum = new Date().toLocaleDateString("nl-BE", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  });
  doc.setFont("helvetica", "italic");
  doc.setFontSize(7);
  doc.setTextColor(...GRIJS);
  doc.text(
    `Indicatieve berekening — opgemaakt op ${datum}. Geen juridisch of fiscaal advies.`,
    14,
    h - 10
  );
}

// ════════════════════════════════════════════════════════════════
// Schenk- vs erfbelasting
// ════════════════════════════════════════════════════════════════
export interface PdfSchijf {
  van: number;
  tot: number;
  tarief: number;
  bedrag: number;
}

export interface BelastingPdfData {
  gewest: string;
  relatieLabel: string;
  goedType: "roerend" | "onroerend";
  waarde: number;
  andereGoederen: number;
  schenking: { totaal: number; effectiefTarief: number; detail: PdfSchijf[]; redenering: string };
  erfenis: {
    totaal: number;
    effectiefTarief: number;
    detail: PdfSchijf[];
    marginaal: boolean;
    redenering: string;
    note: string;
    verdachtePeriode: string;
  };
  verschil: number;
}

export function exportBelastingPdf(d: BelastingPdfData) {
  const doc = new jsPDF();
  const M = 14;
  let y = kop(doc, "Schenking vs Erfbelasting", "België · Tarieven 2026");

  // Parameters
  autoTable(doc, {
    startY: y,
    theme: "plain",
    styles: { fontSize: 9, textColor: DONKER, cellPadding: 1 },
    body: [
      ["Gewest", d.gewest],
      ["Verwantschap", d.relatieLabel],
      ["Type goed", d.goedType === "onroerend" ? "Onroerend goed" : "Roerend / Geld"],
      ["Waarde gesimuleerd goed", euro(d.waarde)],
      ...(d.erfenis.marginaal
        ? [["Andere goederen in nalatenschap", euro(d.andereGoederen)]]
        : []),
    ],
    columnStyles: { 0: { fontStyle: "bold", cellWidth: 70, textColor: GRIJS } },
    margin: { left: M, right: M },
  });
  y = finalY(doc) + 6;

  // Verdict
  const besp = d.verschil > 0;
  doc.setFillColor(besp ? 232 : 250, besp ? 245 : 240, besp ? 233 : 240);
  doc.roundedRect(M, y, 182, 18, 2, 2, "F");
  doc.setFont("helvetica", "bold");
  doc.setFontSize(11);
  doc.setTextColor(...(besp ? ([46, 125, 50] as [number, number, number]) : DONKER));
  const verdictTxt =
    d.verschil > 0
      ? `Besparing via schenking: ${euro(Math.abs(d.verschil))}`
      : d.verschil < 0
      ? `Schenking is duurder: ${euro(Math.abs(d.verschil))}`
      : "Rechten zijn gelijk";
  doc.text(verdictTxt, M + 5, y + 8);
  doc.setFont("helvetica", "normal");
  doc.setFontSize(8);
  doc.setTextColor(...GRIJS);
  doc.text(
    `Schenking: ${pct(d.schenking.effectiefTarief)}   ·   Erfbelasting: ${pct(
      d.erfenis.effectiefTarief
    )}`,
    M + 5,
    y + 14
  );
  y += 24;

  // Schenking detail
  doc.setFont("helvetica", "bold");
  doc.setFontSize(11);
  doc.setTextColor(...GOUD);
  doc.text(`Schenking — ${euro(d.schenking.totaal)}`, M, y);
  y += 3;
  autoTable(doc, {
    startY: y,
    head: [["Schijf", "Tarief", "Belasting"]],
    body: d.schenking.detail.map((s) => [
      `${euro(s.van)} – ${euro(s.tot)}`,
      `${s.tarief} %`,
      euro(s.bedrag),
    ]),
    theme: "grid",
    headStyles: { fillColor: GOUD, textColor: 20, fontSize: 8 },
    styles: { fontSize: 8, textColor: DONKER },
    columnStyles: { 1: { halign: "right" }, 2: { halign: "right" } },
    margin: { left: M, right: M },
  });
  y = finalY(doc) + 3;
  doc.setFont("helvetica", "italic");
  doc.setFontSize(7.5);
  doc.setTextColor(...GRIJS);
  y = schrijfTekst(doc, d.schenking.redenering, M, y, 182) + 5;

  // Erfbelasting detail
  doc.setFont("helvetica", "bold");
  doc.setFontSize(11);
  doc.setTextColor(...BLAUW);
  doc.text(
    `Erfbelasting — ${euro(d.erfenis.totaal)}${d.erfenis.marginaal ? "  (marginaal)" : ""}`,
    M,
    y
  );
  y += 3;
  autoTable(doc, {
    startY: y,
    head: [["Schijf", "Tarief", "Belasting"]],
    body: d.erfenis.detail.map((s) => [
      `${euro(s.van)} – ${euro(s.tot)}`,
      `${s.tarief} %`,
      euro(s.bedrag),
    ]),
    theme: "grid",
    headStyles: { fillColor: BLAUW, textColor: 255, fontSize: 8 },
    styles: { fontSize: 8, textColor: DONKER },
    columnStyles: { 1: { halign: "right" }, 2: { halign: "right" } },
    margin: { left: M, right: M },
  });
  y = finalY(doc) + 3;
  doc.setFont("helvetica", "italic");
  doc.setFontSize(7.5);
  doc.setTextColor(...GRIJS);
  y = schrijfTekst(doc, d.erfenis.redenering, M, y, 182) + 2;
  y = schrijfTekst(doc, `Opmerking: ${d.erfenis.note}`, M, y, 182) + 2;
  y = schrijfTekst(doc, `Verdachte periode: ${d.erfenis.verdachtePeriode}`, M, y, 182) + 5;

  // Disclaimer
  disclaimer(
    doc,
    y,
    "Dit instrument berekent uitsluitend de schenkings- en erfbelasting op één afzonderlijk goed. Het houdt geen rekening met globale vrijstellingen, schulden van de nalatenschap, het beschikbare deel of het huwelijksstelsel. Raadpleeg het notariskantoor te Tervuren voor persoonlijk advies."
  );

  voet(doc);
  doc.save(`schenking-vs-erfbelasting-${d.gewest.toLowerCase()}.pdf`);
}

// ════════════════════════════════════════════════════════════════
// Ereloonberekening
// ════════════════════════════════════════════════════════════════
export interface EreloonPdfData {
  akteLabel: string;
  gewest: string;
  grondslagLabel: string;
  bedrag: number;
  opties: string[];
  honorarium: {
    baremaCode: string;
    baremaOmschrijving: string;
    vastGedeelte: number;
    detail: { label: string; percentage: number; bedrag: number }[];
    honorarium: number;
  };
  aktekosten: { label: string; bedrag: number; opmerking: string };
  btwBasis: number;
  btw: number;
  heffing: { label: string; bedrag: number; detail?: { label: string; percentage: number; bedrag: number }[] } | null;
  retributies: { label: string; bedrag: number }[];
  retributiesTotaal: number;
  totaal: number;
}

export function exportEreloonPdf(d: EreloonPdfData) {
  const doc = new jsPDF();
  const M = 14;
  let y = kop(doc, "Ereloonberekening", "Notarieel ereloon · KB 16.12.1950");

  autoTable(doc, {
    startY: y,
    theme: "plain",
    styles: { fontSize: 9, textColor: DONKER, cellPadding: 1 },
    body: [
      ["Akte", d.akteLabel],
      ["Gewest", d.gewest],
      [d.grondslagLabel, euro(d.bedrag)],
      ["Toegepaste schaal", `${d.honorarium.baremaCode} — ${d.honorarium.baremaOmschrijving}`],
      ...(d.opties.length ? [["Opties", d.opties.join(" · ")]] : []),
    ],
    columnStyles: { 0: { fontStyle: "bold", cellWidth: 70, textColor: GRIJS } },
    margin: { left: M, right: M },
  });
  y = finalY(doc) + 6;

  // Honorarium
  doc.setFont("helvetica", "bold");
  doc.setFontSize(11);
  doc.setTextColor(...DONKER);
  doc.text("Notarieel ereloon", M, y);
  y += 3;
  autoTable(doc, {
    startY: y,
    head: [["Schijf", "Tarief", "Honorarium"]],
    body: [
      ...(d.honorarium.vastGedeelte > 0
        ? [["Vast gedeelte (geïndexeerd 2026)", "—", euro(d.honorarium.vastGedeelte)]]
        : []),
      ...d.honorarium.detail.map((s) => [s.label, `${s.percentage} %`, euro(s.bedrag)]),
    ],
    foot: [["Honorarium (excl. btw)", "", euro(d.honorarium.honorarium)]],
    theme: "grid",
    headStyles: { fillColor: GOUD, textColor: 20, fontSize: 8 },
    footStyles: { fillColor: [245, 245, 245], textColor: DONKER, fontStyle: "bold", fontSize: 8 },
    styles: { fontSize: 8, textColor: DONKER },
    columnStyles: { 1: { halign: "right" }, 2: { halign: "right" } },
    margin: { left: M, right: M },
  });
  y = finalY(doc) + 6;

  // Getarifeerde aktekosten + btw
  doc.setFont("helvetica", "bold");
  doc.setFontSize(11);
  doc.setTextColor(...DONKER);
  doc.text("Getarifeerde aktekosten & btw", M, y);
  y += 3;
  autoTable(doc, {
    startY: y,
    body: [
      [d.aktekosten.label, euro(d.aktekosten.bedrag)],
      ["Honorarium + aktekosten (excl. btw)", euro(d.btwBasis)],
      ["Btw 21 %", euro(d.btw)],
    ],
    foot: [["Ereloon + kosten incl. btw", euro(d.btwBasis + d.btw)]],
    theme: "grid",
    footStyles: { fillColor: [245, 245, 245], textColor: DONKER, fontStyle: "bold", fontSize: 8 },
    styles: { fontSize: 8, textColor: DONKER },
    columnStyles: { 1: { halign: "right" } },
    margin: { left: M, right: M },
  });
  y = finalY(doc) + 2;
  doc.setFont("helvetica", "italic");
  doc.setFontSize(7);
  doc.setTextColor(...GRIJS);
  y = schrijfTekst(doc, d.aktekosten.opmerking, M, y + 2, 182) + 4;

  // Overheidsrechten
  if (d.heffing) {
    doc.setFont("helvetica", "bold");
    doc.setFontSize(11);
    doc.setTextColor(...BLAUW);
    doc.text("Overheidsrechten", M, y);
    y += 3;
    const body = d.heffing.detail?.length
      ? d.heffing.detail.map((s) => [s.label, `${s.percentage} %`, euro(s.bedrag)])
      : [[d.heffing.label, "", euro(d.heffing.bedrag)]];
    autoTable(doc, {
      startY: y,
      head: [["Omschrijving", "Tarief", "Bedrag"]],
      body,
      foot: d.heffing.detail?.length ? [[d.heffing.label, "", euro(d.heffing.bedrag)]] : undefined,
      theme: "grid",
      headStyles: { fillColor: BLAUW, textColor: 255, fontSize: 8 },
      footStyles: { fillColor: [245, 245, 245], textColor: DONKER, fontStyle: "bold", fontSize: 8 },
      styles: { fontSize: 8, textColor: DONKER },
      columnStyles: { 1: { halign: "right" }, 2: { halign: "right" } },
      margin: { left: M, right: M },
    });
    y = finalY(doc) + 6;
  }

  // Hypothecaire retributies
  if (d.retributies.length) {
    doc.setFont("helvetica", "bold");
    doc.setFontSize(11);
    doc.setTextColor(...DONKER);
    doc.text("Hypothecaire retributies (KB 14.09.2016)", M, y);
    y += 3;
    autoTable(doc, {
      startY: y,
      body: d.retributies.map((k) => [k.label, euro(k.bedrag)]),
      foot: [["Subtotaal retributies", euro(d.retributiesTotaal)]],
      theme: "grid",
      footStyles: { fillColor: [245, 245, 245], textColor: DONKER, fontStyle: "bold", fontSize: 8 },
      styles: { fontSize: 8, textColor: DONKER },
      columnStyles: { 1: { halign: "right" } },
      margin: { left: M, right: M },
    });
    y = finalY(doc) + 6;
  }

  // Totaal
  doc.setFillColor(...GOUD);
  doc.roundedRect(M, y, 182, 16, 2, 2, "F");
  doc.setFont("helvetica", "bold");
  doc.setFontSize(12);
  doc.setTextColor(255, 255, 255);
  doc.text("Totale kostprijs (indicatief)", M + 5, y + 10);
  doc.text(euro(d.totaal), 196 - 5, y + 10, { align: "right" });
  y += 22;

  disclaimer(
    doc,
    y,
    "Alle bedragen zijn indicatief. Honoraria volgens KB 16 december 1950 (geconsolideerd 22.11.2022); vaste gedeelten en forfaitaire aktekosten geïndexeerd op 01/01/2026. Hypothecaire retributies volgens KB 14.09.2016. Overheidsrechten volgens de Vlaamse Codex Fiscaliteit. Individualiseerbare uitgaven en diverse bijkomende kosten kunnen van toepassing zijn. Raadpleeg het notariskantoor te Tervuren voor een definitieve afrekening."
  );

  voet(doc);
  doc.save(`ereloon-${d.akteLabel.toLowerCase().replace(/[^a-z]+/g, "-")}.pdf`);
}

// ── Hulp ───────────────────────────────────────────────────────
function schrijfTekst(doc: jsPDF, tekst: string, x: number, y: number, breedte: number): number {
  const regels = doc.splitTextToSize(tekst, breedte);
  doc.text(regels, x, y);
  return y + regels.length * 3.5;
}

function disclaimer(doc: jsPDF, y: number, tekst: string) {
  const M = 14;
  doc.setDrawColor(220, 220, 220);
  doc.setFillColor(248, 248, 248);
  const regels = doc.splitTextToSize(tekst, 174);
  const hoogte = regels.length * 3.6 + 10;
  doc.roundedRect(M, y, 182, hoogte, 2, 2, "FD");
  doc.setFont("helvetica", "bold");
  doc.setFontSize(7.5);
  doc.setTextColor(...GOUD);
  doc.text("Waarschuwing", M + 4, y + 6);
  doc.setFont("helvetica", "normal");
  doc.setTextColor(...GRIJS);
  doc.text(regels, M + 4, y + 11);
}
