import React, { useEffect, useMemo, useRef, useState, useDeferredValue, startTransition } from "react";
import {
  getProducts,
  getCategories as apiGetCategories,
  renameCategory as apiRenameCategory,
  deleteCategory as apiDeleteCategory,
  updateProduct,
} from "../../api";
import { FiEye, FiEdit2, FiX, FiPlus, FiTrash2, FiCheck, FiSearch } from "react-icons/fi";
import { createPortal } from "react-dom";


/* ---------- Helpers ---------- */
const euro = (cents) => ((Number(cents ?? 0)) / 100).toFixed(2);
const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
const uniq = (arr) => Array.from(new Set(arr));
const displayVal = (v) => (v === 0 ? 0 : v ?? "–"); // 0 nicht verschlucken

export default function ProductsPage() {
  const [rows, setRows] = useState([]);
  const [err, setErr] = useState(null);
  const [loading, setLoading] = useState(true);

  // Toolbar-States
  const [search, setSearch] = useState("");
  const deferredSearch = useDeferredValue(search);
  const [category, setCategory] = useState("ALLE");

  // Sortierung
  const [sortBy, setSortBy] = useState("name");
  const [sortDir, setSortDir] = useState("asc");

  // Modals
  const [viewItem, setViewItem] = useState(null);
  const [editItem, setEditItem] = useState(null);
  const [catMgrOpen, setCatMgrOpen] = useState(false);
  const [reassignInfo, setReassignInfo] = useState(null); // {oldCat}

  // Kategorien-State (Serverquelle + „ALLE“)
  const [categories, setCategories] = useState(["ALLE"]);

  useEffect(() => {
    refreshProductsAndCategories();
  }, []);

  async function refreshProductsAndCategories() {
    try {
      const [data, cats] = await Promise.all([getProducts(), apiGetCategories()]);
      setRows(Array.isArray(data) ? data : []);
      setCategories(["ALLE", ...cats]);
    } catch (e) {
      setErr(e);
    } finally {
      setLoading(false);
    }
  }

  // Filter + Suche
const filtered = useMemo(() => {
    const q = deferredSearch.trim().toLowerCase();
    return rows.filter((r) => {
      const catOk = category === "ALLE" || (r.category ?? "") === category;
      if (!catOk) return false;
      if (!q) return true;
      const hay = [r.name, r.category, r.supplier_number, String(r.id)]
        .filter(Boolean)
        .join(" ")
        .toLowerCase();
      return hay.includes(q);
    });
  }, [rows, category, deferredSearch]);

  // Spalten
  const columns = useMemo(() => {
    const base = [
      { id: "id", label: "ID", get: (p) => p.id, mono: true, type: "num" },
      { id: "name", label: "Name", get: (p) => p.name ?? "" },
      {
        id: "price_cents",
        label: "Preis (€)",
        get: (p) => Number(p.price_cents ?? 0),
        render: (p) => euro(p.price_cents),
        mono: true,
        type: "num",
      },
      { id: "category", label: "Kategorie", get: (p) => p.category ?? "" },
      { id: "stock", label: "Bestand", get: (p) => (p.stock ?? p.stock === 0 ? p.stock : null), type: "num" },
    ];
    const hasVolume = filtered.some((r) => r.volume_ml !== undefined && r.volume_ml !== null);
    if (hasVolume) {
      base.splice(4, 0, {
        id: "volume_ml",
        label: "Volumen (ml)",
        get: (p) => (p.volume_ml ?? p.volume_ml === 0 ? p.volume_ml : null),
        type: "num",
      });
    }
    return base;
  }, [filtered]);

  const sorted = useMemo(() => {
    const col = columns.find((c) => c.id === sortBy) ?? columns[0];
    const arr = filtered.slice();
    arr.sort((a, b) => {
      const av = col.get(a);
      const bv = col.get(b);
      let res;
      if (col.type === "num") {
        const ax = av == null ? -Infinity : Number(av);
        const bx = bv == null ? -Infinity : Number(bv);
        res = ax - bx;
      } else {
        res = cmp(String(av ?? ""), String(bv ?? ""));
      }
      return sortDir === "asc" ? res : -res;
    });
    return arr;
  }, [filtered, columns, sortBy, sortDir]);

  const toggleSort = (id) => {
   if (id === sortBy) {
     startTransition(() => setSortDir((d) => (d === "asc" ? "desc" : "asc")));
     } else {
     startTransition(() => { setSortBy(id); setSortDir("asc"); });
   }
 };
  const sortMark = (id) => (id !== sortBy ? "∙" : sortDir === "asc" ? "▲" : "▼");

  // Kategorie-Operationen
  const addCategory = (name) => {
    const n = (name || "").trim();
    if (!n || n === "ALLE") return;
    setCategories((prev) => (prev.includes(n) ? prev : [...prev, n].sort((a, b) => a.localeCompare(b, "de"))));
  };

  async function onRenameCategory(oldName, newName) {
    const nn = (newName || "").trim();
    if (!nn || nn === "ALLE" || oldName === "ALLE") return;
    await apiRenameCategory(oldName, nn);
    await refreshProductsAndCategories();
    if (category === oldName) setCategory(nn);
  }

  function requestDeleteCategory(cat) {
    if (cat === "ALLE") return;
    const affected = rows.filter((r) => r.category === cat).length;
    if (affected === 0) {
      setCategories((prev) => prev.filter((x) => x !== cat));
      if (category === cat) setCategory("ALLE");
    } else {
      setReassignInfo({ oldCat: cat });
      setCatMgrOpen(false);
    }
  }

  async function performReassignAndDelete(oldCat, targetCat) {
    const tgt = (targetCat || "").trim();
    if (!tgt || tgt === "ALLE") return;
    await apiDeleteCategory(oldCat, tgt);
    await refreshProductsAndCategories();
    if (category === oldCat) setCategory(tgt);
    setReassignInfo(null);
  }

  async function saveEditedProduct(updated) {
    const payload = {
      name: updated.name,
      category: updated.category,
      volume_ml: updated.volume_ml,
      price_cents: updated.price_cents,
      supplier_number: updated.supplier_number ?? null,
      stock: updated.stock,
      is_active: updated.is_active,
      // NEU:
      pack_size: Math.max(1, Number(updated.pack_size) || 1),
      purchase_price_cents: Number(updated.purchase_price_cents) || 0,
    };
    await updateProduct(updated.id, payload);
    await refreshProductsAndCategories();
    setEditItem(null);
  }


  if (loading) return <div className="text-white">Lade Produkte…</div>;
  if (err) return <div className="text-red-300">Fehler: {String(err.message || err)}</div>;

  return (
    <div className="rounded-2xl bg-white/5 border-2 border-cyan-400/20 p-5 text-white/80">
      <h2 className="text-white/90 font-semibold mb-4">Produkte</h2>

      {/* Toolbar */}
      <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between mb-4">
        {/* Kategorien */}
        <div className="flex flex-wrap items-center gap-2">
          {categories.map((c) => (
            <button
              key={c}
              onClick={() => setCategory(c)}
              className={`px-3 py-1 rounded-full border transition ${
                category === c
                  ? "bg-cyan-600 border-cyan-400 text-white"
                  : "bg-transparent border-cyan-400/30 text-white/80 hover:bg-cyan-600/30"
              }`}
            >
              {c}
            </button>
          ))}
          <button
            onClick={() => setCatMgrOpen(true)}
            className="ml-1 inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/10 border border-white/20 hover:bg-white/15"
          >
            <FiEdit2 />
            <span>Kategorien</span>
          </button>
        </div>

        {/* Suche */}
        <div className="flex items-center gap-2">
          <div className="relative">
            <FiSearch className="absolute left-3 top-1/2 -translate-y-1/2 text-white/40" />
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Suchen (Name, Kategorie, ID, Lieferantennr.)"
              className="pl-9 pr-10 py-2 rounded-lg bg-white/10 border border-white/20 text-white placeholder-white/40 w-80 focus:outline-none focus:ring-2 focus:ring-cyan-500"
            />
          </div>
          {search && (
            <button
              onClick={() => setSearch("")}
              className="p-2 rounded-lg bg-white/10 hover:bg-white/15 border border-white/20"
              title="Suche löschen"
            >
              <FiX />
            </button>
          )}
        </div>
      </div>

      {/* Tabelle */}
      <div className="overflow-x-auto" style={{ contentVisibility: "auto", containIntrinsicSize: "600px" }}>
        <table className="min-w-full text-sm">
          <thead className="text-white/60">
            <tr>
              {columns.map((c) => (
                <th key={c.id} className="text-left py-2 pr-4">
                  <button
                    onClick={() => toggleSort(c.id)}
                    className="inline-flex items-center gap-2 hover:text-white focus:outline-none"
                    aria-sort={c.id !== sortBy ? "none" : sortDir === "asc" ? "ascending" : "descending"}
                    title={`Nach ${c.label} sortieren`}
                  >
                    <span>{c.label}</span>
                    <span className="text-xs opacity-70">{sortMark(c.id)}</span>
                  </button>
                </th>
              ))}
              <th className="text-left py-2 pr-4">Aktionen</th>
            </tr>
          </thead>
          <tbody>
            {sorted.map((p) => (
              <tr key={p.id} className="border-t border-white/10">
                {columns.map((c) => (
                  <td key={c.id} className={`py-2 pr-4 ${c.mono ? "font-mono" : ""}`}>
                    {c.render ? c.render(p) : displayVal(c.get(p))}
                  </td>
                ))}
                <td className="py-2 pr-4">
                  <div className="flex items-center gap-3">
                    <button
                      onClick={() => setViewItem(p)}
                      className="p-2 rounded bg-white/5 hover:bg-white/10 border border-white/10"
                      title="Ansehen"
                      aria-label="Ansehen"
                    >
                      <FiEye />
                    </button>
                    <button
                      onClick={() => setEditItem(p)}
                      className="p-2 rounded bg-white/5 hover:bg-white/10 border border-white/10"
                      title="Bearbeiten"
                      aria-label="Bearbeiten"
                    >
                      <FiEdit2 />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
            {sorted.length === 0 && (
              <tr>
                <td className="py-4 text-white/60" colSpan={columns.length + 1}>
                  Keine Produkte gefunden.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Modals */}
      {viewItem && (
        <Modal onClose={() => setViewItem(null)} title="Produkt ansehen">
          <DetailView item={viewItem} />
        </Modal>
      )}

      {editItem && (
        <Modal onClose={() => setEditItem(null)} title="Produkt bearbeiten">
          <EditForm
            item={editItem}
            categories={categories.filter((c) => c !== "ALLE")}
            onCancel={() => setEditItem(null)}
            onSave={saveEditedProduct}
          />
        </Modal>
      )}

      {catMgrOpen && (
        <Modal onClose={() => setCatMgrOpen(false)} title="Kategorien verwalten">
          <CategoryManager
            categories={categories.filter((c) => c !== "ALLE")}
            onAdd={addCategory}
            onRename={onRenameCategory}
            onDelete={requestDeleteCategory}
          />
        </Modal>
      )}

      {reassignInfo && (
        <Modal onClose={() => setReassignInfo(null)} title="Kategorie neu zuweisen">
          <ReassignCategoryForm
            oldCat={reassignInfo.oldCat}
            categories={categories.filter((c) => c !== "ALLE" && c !== reassignInfo.oldCat)}
            onCancel={() => setReassignInfo(null)}
            onConfirm={(targetCat) => performReassignAndDelete(reassignInfo.oldCat, targetCat)}
          />
        </Modal>
      )}
    </div>
  );
}

/* ---------- Sub-Komponenten ---------- */

function Modal({ title, children, onClose }) {
  // ESC schließt + Body-Scroll locken
  useEffect(() => {
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prevOverflow;
      document.removeEventListener("keydown", onKey);
    };
  }, [onClose]);

  const node = (
    <div className="fixed inset-0 z-[9999]">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/60" onClick={onClose} />
      {/* Centering-Layer */}
      <div className="absolute inset-0 p-4 flex items-center justify-center">
        <div
          role="dialog"
          aria-modal="true"
          className="relative w-full max-w-2xl rounded-2xl bg-slate-900 border border-cyan-400/20 shadow-xl"
        >
          <div className="flex items-center justify-between px-5 py-3 border-b border-white/10">
            <h3 className="text-white/90 font-semibold">{title}</h3>
            <button
              onClick={onClose}
              className="p-2 rounded hover:bg-white/10 text-white/70"
              aria-label="Schließen"
              title="Schließen"
            >
              <FiX />
            </button>
          </div>
          <div className="p-5 text-white/80">{children}</div>
        </div>
      </div>
    </div>
  );

  return createPortal(node, document.body);
}


function DetailView({ item }) {
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
      <InfoRow label="ID" value={<code>{item.id}</code>} />
      <InfoRow label="Name" value={item.name ?? "–"} />
      <InfoRow label="Preis" value={`${euro(item.price_cents)} €`} />
      {/* NEU: Einkaufspreis & Pack-Größe */}
      {"purchase_price_cents" in item && (
        <InfoRow label="Einkaufspreis" value={`${euro(item.purchase_price_cents)} €`} />
      )}
      {"pack_size" in item && (
        <InfoRow label="Pack-Größe" value={displayVal(item.pack_size)} />
      )}
      <InfoRow label="Kategorie" value={item.category ?? "–"} />
      {"volume_ml" in item && <InfoRow label="Volumen (ml)" value={displayVal(item.volume_ml)} />}
      <InfoRow label="Bestand" value={displayVal(item.stock)} />
      <InfoRow label="Aktiv" value={item.is_active ? "ja" : "nein"} />
      <InfoRow label="Lieferantennr." value={item.supplier_number ?? "–"} />
    </div>
  );
}


function InfoRow({ label, value }) {
  return (
    <div className="flex items-center justify-between border-b border-white/10 py-2">
      <div className="text-white/60">{label}</div>
      <div className="text-white">{value}</div>
    </div>
  );
}

/* ===== Edit-Form mit Animated Switch + Category Dropdown ===== */

function EditForm({ item, onSave, onCancel, categories }) {
  const [form, setForm] = useState({
    id: item.id,
    name: item.name ?? "",
    price_cents: Number(item.price_cents ?? 0),
    // NEU:
    purchase_price_cents: Number(item.purchase_price_cents ?? 0),
    pack_size: Number(item.pack_size ?? 1),
    category: item.category ?? "",
    stock: item.stock ?? 0,
    volume_ml: item.volume_ml ?? "",
    is_active: item.is_active ?? true,
    supplier_number: item.supplier_number ?? "",
  });
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  return (
    <form
      className="space-y-4"
      onSubmit={(e) => {
        e.preventDefault();
        onSave({
          ...item,
          ...form,
          price_cents: Number(form.price_cents) || 0,
          // NEU:
          purchase_price_cents: Number(form.purchase_price_cents) || 0,
          pack_size: Math.max(1, Number(form.pack_size) || 1),
          stock: form.stock === "" ? null : Number(form.stock),
          volume_ml: form.volume_ml === "" ? null : Number(form.volume_ml),
        });
      }}
    >
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Field label="Name">
          <input
            className="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
            value={form.name}
            onChange={(e) => set("name", e.target.value)}
            required
          />
        </Field>

        <Field label="Kategorie">
          <CategorySelect
            value={form.category}
            onChange={(v) => set("category", v)}
            options={categories}
          />
        </Field>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Field label="Verkaufspreis (Cent)">
          <input
            type="number"
            className="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
            value={form.price_cents}
            onChange={(e) => set("price_cents", e.target.value)}
            min={0}
          />
        </Field>
        <Field label="Einkaufspreis (Cent)">
          <input
            type="number"
            className="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
            value={form.purchase_price_cents}
            onChange={(e) => set("purchase_price_cents", e.target.value)}
            min={0}
          />
        </Field>
        <Field label="Pack-Größe (Stk/Pack)">
          <input
            type="number"
            className="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
            value={form.pack_size}
            onChange={(e) => set("pack_size", e.target.value)}
            min={1}
          />
        </Field>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Field label="Volumen (ml)">
          <input
            type="number"
            className="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
            value={form.volume_ml}
            onChange={(e) => set("volume_ml", e.target.value)}
            min={0}
          />
        </Field>
        <Field label="Bestand">
          <input
            type="number"
            className="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
            value={form.stock}
            onChange={(e) => set("stock", e.target.value)}
            min={0}
          />
        </Field>
        <Field label="Lieferantennr.">
          <input
            className="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
            value={form.supplier_number}
            onChange={(e) => set("supplier_number", e.target.value)}
          />
        </Field>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Field label="Aktiv">
          <Switch
            checked={!!form.is_active}
            onChange={(v) => set("is_active", v)}
            labelOn="aktiv"
            labelOff="inaktiv"
          />
        </Field>

      </div>

      <div className="flex justify-end gap-3 pt-2">
        <button
          type="button"
          onClick={onCancel}
          className="px-4 py-2 rounded bg-white/10 border border-white/20 hover:bg-white/15"
        >
          Abbrechen
        </button>
        <button
          type="submit"
          className="px-4 py-2 rounded bg-cyan-600 hover:bg-cyan-700 text-white"
        >
          <span className="inline-flex items-center gap-2"><FiCheck /> Speichern</span>
        </button>
      </div>
    </form>
  );
}


function Field({ label, children }) {
  return (
    <label className="block">
      <div className="text-white/60 mb-1">{label}</div>
      {children}
    </label>
  );
}

/* ===== Schönes Kategorie-Dropdown mit Filter ===== */

function CategorySelect({ value, onChange, options, placeholder = "Kategorie wählen" }) {
  const [open, setOpen] = useState(false);
  const rootRef = useRef(null);

  // Für stabile Anzeige ohne Duplikate/Nulls
  const cleanedOpts = useMemo(
    () => Array.from(new Set((options || []).filter(Boolean))),
    [options]
  );

  // Klick außerhalb schließt Dropdown
  useEffect(() => {
    if (!open) return;
    const onDocClick = (e) => {
      if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("mousedown", onDocClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDocClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  return (
    <div className="relative" ref={rootRef}>
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="w-full flex items-center justify-between px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
        aria-haspopup="listbox"
        aria-expanded={open}
      >
        <span className="truncate">{value || placeholder}</span>
        <span className={`text-white/50 transition-transform ${open ? "rotate-180" : ""}`}>▼</span>
      </button>

      {open && (
        <div className="absolute z-50 mt-2 w-full rounded-xl bg-slate-900 border border-white/15 shadow-xl">
          <ul className="max-h-56 overflow-auto py-1" role="listbox">
            {cleanedOpts.length === 0 && (
              <li className="px-3 py-2 text-white/50">Keine Kategorien.</li>
            )}
            {cleanedOpts.map((opt) => (
              <li key={opt}>
                <button
                  type="button"
                  onClick={() => {
                    onChange(opt);
                    setOpen(false); // schließt nach Auswahl automatisch
                  }}
                  className={`w-full text-left px-3 py-2 hover:bg-white/10 ${
                    value === opt ? "bg-cyan-600/30" : ""
                  }`}
                  role="option"
                  aria-selected={value === opt}
                >
                  {opt}
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}


/* ===== Animated Switch (ohne externe Lib) ===== */

function Switch({ checked, onChange, labelOn = "On", labelOff = "Off" }) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      onClick={() => onChange(!checked)}
      className={`relative inline-flex h-6 w-12 items-center rounded-full transition
        ${checked ? "bg-cyan-600" : "bg-white/20"} focus:outline-none border border-white/20`}
      title={checked ? labelOn : labelOff}
    >
      <span
        className={`inline-block h-5 w-5 transform rounded-full bg-white shadow transition
          ${checked ? "translate-x-6" : "translate-x-1"}`}
      />
      <span className="sr-only">{checked ? labelOn : labelOff}</span>
    </button>
  );
}

/* ---- Kategorien-Manager ---- */

function CategoryManager({ categories, onAdd, onRename, onDelete }) {
  const [newName, setNewName] = useState("");
  const [renaming, setRenaming] = useState(null);
  const [renameVal, setRenameVal] = useState("");

  return (
    <div className="space-y-6">
      <div className="flex gap-2">
        <input
          className="flex-1 px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
          placeholder="Neue Kategorie"
          value={newName}
          onChange={(e) => setNewName(e.target.value)}
        />
        <button
          onClick={() => {
            const n = newName.trim();
            if (!n) return;
            onAdd(n);
            setNewName("");
          }}
          className="px-3 py-2 rounded bg-cyan-600 hover:bg-cyan-700 text-white inline-flex items-center gap-2"
        >
          <FiPlus /> Hinzufügen
        </button>
      </div>

      <ul className="divide-y divide-white/10 border border-white/10 rounded-lg">
        {categories.length === 0 && (
          <li className="px-3 py-3 text-white/60">Keine eigenen Kategorien.</li>
        )}
        {categories.map((c) => (
          <li key={c} className="px-3 py-2 flex items-center justify-between">
            {renaming === c ? (
              <div className="flex items-center gap-2 w-full">
                <input
                  className="flex-1 px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
                  value={renameVal}
                  onChange={(e) => setRenameVal(e.target.value)}
                  autoFocus
                />
                <button
                  className="px-3 py-2 rounded bg-cyan-600 hover:bg-cyan-700 text-white"
                  onClick={() => {
                    const val = renameVal.trim();
                    if (val) onRename(c, val);
                    setRenaming(null);
                    setRenameVal("");
                  }}
                >
                  Umbenennen
                </button>
                <button
                  className="px-3 py-2 rounded bg-white/10 border border-white/20"
                  onClick={() => {
                    setRenaming(null);
                    setRenameVal("");
                  }}
                >
                  Abbrechen
                </button>
              </div>
            ) : (
              <>
                <span className="text-white">{c}</span>
                <div className="flex items-center gap-2">
                  <button
                    className="p-2 rounded bg-white/5 hover:bg-white/10 border border-white/10"
                    title="Kategorie umbenennen"
                    onClick={() => {
                      setRenaming(c);
                      setRenameVal(c);
                    }}
                  >
                    <FiEdit2 />
                  </button>
                  <button
                    className="p-2 rounded bg-white/5 hover:bg-white/10 border border-white/10 text-red-300"
                    title="Kategorie löschen"
                    onClick={() => onDelete(c)}
                  >
                    <FiTrash2 />
                  </button>
                </div>
              </>
            )}
          </li>
        ))}
      </ul>
      <p className="text-white/50 text-sm">
        Hinweis: Das Löschen einer genutzten Kategorie erfordert die Neuzuordnung aller zugehörigen Produkte.
      </p>
    </div>
  );
}

/* ---- Reassign-Dialog ---- */

function ReassignCategoryForm({ oldCat, categories, onCancel, onConfirm }) {
  const [target, setTarget] = useState(categories[0] ?? "");
  const [custom, setCustom] = useState("");

  const effectiveTarget = custom.trim() || target;

  return (
    <form
      className="space-y-4"
      onSubmit={(e) => {
        e.preventDefault();
        if (!effectiveTarget) return;
        onConfirm(effectiveTarget);
      }}
    >
      <p>
        Die Kategorie <b>{oldCat}</b> wird aktuell verwendet. Bitte wähle eine{" "}
        <b>neue Kategorie</b> für alle betroffenen Produkte oder gib eine neue ein.
      </p>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Field label="Zielkategorie auswählen">
          <select
            className="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
            value={target}
            onChange={(e) => setTarget(e.target.value)}
          >
            {categories.length === 0 && <option value="">(keine vorhanden)</option>}
            {categories.map((c) => (
              <option key={c} value={c}>
                {c}
              </option>
            ))}
          </select>
        </Field>
        <Field label="oder neue Zielkategorie anlegen">
          <input
            className="w-full px-3 py-2 rounded bg-white/10 border border-white/20 text-white"
            placeholder="Neue Kategorie"
            value={custom}
            onChange={(e) => setCustom(e.target.value)}
          />
        </Field>
      </div>

      <div className="flex justify-end gap-3 pt-2">
        <button
          type="button"
          onClick={onCancel}
          className="px-4 py-2 rounded bg-white/10 border border-white/20 hover:bg-white/15"
        >
          Abbrechen
        </button>
        <button
          type="submit"
          className="px-4 py-2 rounded bg-cyan-600 hover:bg-cyan-700 text-white"
        >
          <span className="inline-flex items-center gap-2">
            <FiCheck /> Neuzuordnen & löschen
          </span>
        </button>
      </div>
    </form>
  );
}
