"use client";

import { useState } from "react";
import {
  relatieLabels,
  relatieIcoon,
  relatieOpties,
  type Relatie,
} from "@/data/belastingen";
import { euro, parseBedrag } from "@/lib/format";

// ── Gedeeld model voor meerdere begunstigden ─────────────────────────────────

export interface Begunstigde {
  id: string;
  relatie: Relatie;
  /** Enkel relevant bij rechte_lijn_partner: partner vs kind/afstammeling. */
  isPartner: boolean;
  /** Aandeel als string — percentage ("50"), breukdeel ("1/2") of eurobedrag ("150000"). */
  aandeelStr: string;
}

export function nieuweBegunstigde(relatie: Relatie = "rechte_lijn_partner"): Begunstigde {
  return { id: `b${Date.now()}`, relatie, isPartner: false, aandeelStr: "100" };
}

/**
 * Parseert percentages ("50"), breukdelen ("1/2") of eurobedragen.
 * Waarden > 100 worden als eurobedrag behandeld wanneer totaalBedrag opgegeven.
 */
export function parseAandeel(b: Begunstigde, totaalBedrag?: number): number {
  const s = b.aandeelStr.trim();
  const m = s.replace(",", ".").match(/^(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)$/);
  if (m) {
    const den = parseFloat(m[2]);
    return den !== 0 ? Math.max(0, (parseFloat(m[1]) / den) * 100) : 0;
  }
  const num = parseBedrag(s);
  if (num > 100 && totaalBedrag && totaalBedrag > 0) {
    return Math.max(0, (num / totaalBedrag) * 100);
  }
  return Math.max(0, num);
}

function isBreukNotatie(s: string): boolean {
  return s.trim().includes("/");
}

function pctNaarBreuk(pct: number): string {
  const veelgebruikt: Array<[number, string]> = [
    [100, "1/1"], [50, "1/2"], [33.33, "1/3"], [66.67, "2/3"],
    [25, "1/4"], [75, "3/4"], [20, "1/5"], [40, "2/5"],
    [60, "3/5"], [80, "4/5"], [16.67, "1/6"], [83.33, "5/6"],
  ];
  const r = Math.round(pct * 100) / 100;
  for (const [p, f] of veelgebruikt) {
    if (Math.abs(r - p) < 0.5) return f;
  }
  return String(Math.round(pct));
}

/** Voegt een begunstigde toe als gelijk breukdeel (1/n) — standaardverdeling. */
export function voegBegunstigdeToeGelijk(prev: Begunstigde[]): Begunstigde[] {
  const n = prev.length + 1;
  return [
    ...prev.map((x) => ({ ...x, aandeelStr: `1/${n}` })),
    { ...nieuweBegunstigde(), aandeelStr: `1/${n}` },
  ];
}

type AandeelModus = "breuk" | "pct" | "bedrag";

export default function BegunstigdenEditor({
  begunstigden,
  onChange,
  totaalBedrag,
  toonPartnerToggle = false,
  compact = false,
  toonRelatie = true,
  itemLabel = "Begunstigde",
}: {
  begunstigden: Begunstigde[];
  onChange: (b: Begunstigde[]) => void;
  /** Totale waarde van het goed — vereist voor eurobedrag-modus en €-weergave. */
  totaalBedrag: number;
  /** Toon de partner/afstammeling-subtoggle bij rechte_lijn_partner. */
  toonPartnerToggle?: boolean;
  /** Kleinere typografie voor smalle invoerformulieren. */
  compact?: boolean;
  /** Toon de relatie-knoppen (relevant voor begunstigden, niet voor schenkers). */
  toonRelatie?: boolean;
  /** Label per item, bv. "Begunstigde" of "Schenker" (gevolgd door volgnummer). */
  itemLabel?: string;
}) {
  const [aandeelModus, setAandeelModus] = useState<AandeelModus>("breuk");

  const totaalPct = begunstigden.reduce((s, b) => s + parseAandeel(b, totaalBedrag), 0);
  const aandeelOk = Math.abs(totaalPct - 100) < 0.1;
  const relatieBtnCls = compact ? "px-2 py-1 text-[11px]" : "px-2 py-1 text-xs";

  function update(id: string, patch: Partial<Begunstigde>) {
    onChange(begunstigden.map((x) => (x.id === id ? { ...x, ...patch } : x)));
  }

  function switchModus(newModus: AandeelModus) {
    if (newModus === aandeelModus) return;
    onChange(
      begunstigden.map((b) => {
        const pct = parseAandeel(b, totaalBedrag);
        if (newModus === "breuk") return { ...b, aandeelStr: pctNaarBreuk(pct) };
        if (newModus === "pct") return { ...b, aandeelStr: String(Math.round(pct * 10) / 10) };
        // bedrag
        return totaalBedrag > 0
          ? { ...b, aandeelStr: String(Math.round((totaalBedrag * pct) / 100)) }
          : b;
      })
    );
    setAandeelModus(newModus);
  }

  function handleVoegToe() {
    if (aandeelModus === "bedrag" && totaalBedrag > 0) {
      const n = begunstigden.length + 1;
      const gelijk = Math.round(totaalBedrag / n);
      onChange([
        ...begunstigden.map((x) => ({ ...x, aandeelStr: String(gelijk) })),
        { ...nieuweBegunstigde(), aandeelStr: String(gelijk) },
      ]);
    } else {
      onChange(voegBegunstigdeToeGelijk(begunstigden));
    }
  }

  return (
    <div className="space-y-2">
      {/* Aandeel-modus toggle */}
      <div className="flex justify-end gap-1">
        {(["breuk", "pct", "bedrag"] as AandeelModus[]).map((m) => (
          <button
            key={m}
            type="button"
            disabled={m === "bedrag" && totaalBedrag <= 0}
            onClick={() => switchModus(m)}
            className={`text-[10px] px-1.5 py-0.5 rounded border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${
              aandeelModus === m
                ? "bg-brand-100 text-brand-700 border-brand-300"
                : "text-slate-400 border-slate-200 hover:border-brand-200 hover:text-brand-500"
            }`}
          >
            {m === "breuk" ? "⅓ Breuk" : m === "pct" ? "% Pct." : "€ Bedrag"}
          </button>
        ))}
      </div>

      {begunstigden.map((b, idx) => {
        const pct = parseAandeel(b, totaalBedrag);
        const isBedragModus = aandeelModus === "bedrag";
        const toonPctAfleiding = isBreukNotatie(b.aandeelStr) || isBedragModus;

        return (
          <div
            key={b.id}
            className={`bg-slate-50 border border-slate-200 rounded-xl space-y-2 ${compact ? "p-3" : "p-4"}`}
          >
            <div className="flex items-center justify-between">
              <span className={`font-semibold ${compact ? "text-xs text-slate-500" : "text-xs text-slate-600"}`}>
                {itemLabel} {idx + 1}
              </span>
              {begunstigden.length > 1 && (
                <button
                  type="button"
                  onClick={() => onChange(begunstigden.filter((x) => x.id !== b.id))}
                  className="text-xs text-slate-400 hover:text-red-500"
                >
                  ✕
                </button>
              )}
            </div>
            {toonRelatie && (
              <div className="flex flex-wrap gap-1">
                {relatieOpties.map((r) => (
                  <button
                    key={r}
                    type="button"
                    onClick={() => update(b.id, { relatie: r })}
                    className={`${relatieBtnCls} rounded-md border transition-colors ${
                      b.relatie === r
                        ? "bg-brand-600 text-white border-brand-600"
                        : "text-slate-600 border-slate-300 hover:border-brand-300"
                    }`}
                  >
                    {compact ? relatieLabels[r] : `${relatieIcoon[r]} ${relatieLabels[r]}`}
                  </button>
                ))}
              </div>
            )}
            {toonPartnerToggle && b.relatie === "rechte_lijn_partner" && (
              <div className="flex gap-1.5">
                {(["afstammeling", "partner"] as const).map((rol) => (
                  <button
                    key={rol}
                    type="button"
                    onClick={() => update(b.id, { isPartner: rol === "partner" })}
                    className={`px-2 py-1 text-[11px] rounded border transition-colors ${
                      (rol === "partner") === b.isPartner
                        ? "bg-brand-100 text-brand-700 border-brand-300"
                        : "text-slate-500 border-slate-200 hover:border-brand-200"
                    }`}
                  >
                    {rol === "partner" ? "🤝 Partner" : "👶 Kind/afstammeling"}
                  </button>
                ))}
              </div>
            )}
            <div className="flex items-center gap-2 flex-wrap">
              <span className={`shrink-0 text-slate-500 ${compact ? "text-[11px]" : "text-xs"}`}>
                {isBedragModus ? "Bedrag (€):" : "Aandeel:"}
              </span>
              <input
                type="text"
                inputMode="decimal"
                value={b.aandeelStr}
                onChange={(e) => update(b.id, { aandeelStr: e.target.value })}
                placeholder={
                  aandeelModus === "breuk" ? "1/2" :
                  aandeelModus === "bedrag" ? "bv. 150000" : "50"
                }
                className={`border border-slate-300 rounded text-center focus:outline-none focus:ring-1 focus:ring-brand-400 ${
                  isBedragModus
                    ? compact ? "w-24 text-xs px-1.5 py-0.5" : "w-28 text-xs px-2 py-1"
                    : compact ? "w-14 text-xs px-1.5 py-0.5" : "w-16 text-xs px-2 py-1"
                }`}
              />
              {toonPctAfleiding ? (
                <span className={`text-brand-500 font-medium ${compact ? "text-[11px]" : "text-xs"}`}>
                  = {Math.round(pct * 10) / 10}%
                </span>
              ) : (
                <span className={`text-slate-400 ${compact ? "text-[11px]" : "text-xs"}`}>%</span>
              )}
              {!isBedragModus && totaalBedrag > 0 && pct > 0 && (
                <span className={`text-slate-400 ${compact ? "text-[11px]" : "text-xs"}`}>
                  · {euro(totaalBedrag * (pct / 100))}
                </span>
              )}
            </div>
          </div>
        );
      })}

      <div
        className={`px-2.5 py-1.5 rounded-md ${compact ? "text-[11px]" : "text-xs"} ${
          aandeelOk ? "text-emerald-700 bg-emerald-50" : "text-amber-700 bg-amber-50"
        }`}
      >
        Totaal: {Math.round(totaalPct * 10) / 10}% {aandeelOk ? "✓" : "⚠ verwacht 100%"}
      </div>

      <button
        type="button"
        onClick={handleVoegToe}
        className={`w-full text-xs border border-dashed border-brand-300 text-brand-600 rounded-xl hover:bg-brand-50 transition-colors ${
          compact ? "py-1.5" : "py-2"
        }`}
      >
        + Begunstigde toevoegen
      </button>
    </div>
  );
}
