import React, { useEffect, useMemo, useRef, useState } from "react";
import { listTopupsAdmin, patchTopupStatus, getUsersLite, getPaypalSettings, updatePaypalSettings, createTopupAdmin } from "../../api";

const euro = (c) => (c ?? 0) / 100;
const fmt = new Intl.NumberFormat("de-DE", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const fmtDT = new Intl.DateTimeFormat("de-DE", { dateStyle: "short", timeStyle: "medium", timeZone: "Europe/Berlin" });
const SHOW_CREATE = false;

const toText = (v) => {
  if (v == null) return "—";
  if (typeof v === "object") {
    try { return JSON.stringify(v); } catch { return "[obj]"; }
  }
  return String(v);
};


const STATUS_LABELS_DE = {
  pending:   "ausstehend",
  confirmed: "bestätigt",
  rejected:  "abgelehnt",
};
const statusLabel = (s) => STATUS_LABELS_DE[s] ?? String(s ?? "");

function Pill({ status }) {
  const map = {
    pending:   "bg-yellow-500/20 text-yellow-300 border-yellow-500/30",
    confirmed: "bg-emerald-500/20 text-emerald-300 border-emerald-500/30",
    rejected:  "bg-rose-500/20 text-rose-300 border-rose-500/30",
  };
  return (
    <span className={`px-2 py-0.5 rounded-full text-xs border ${map[status] || "bg-white/10 text-white/70 border-white/20"}`}>
      {statusLabel(status)}
    </span>
  );
}


/** Kleiner Avatar (Initialen) */
function Initials({ label }) {
  const txt = String(label || "")
    .split(/\s+/).filter(Boolean).slice(0,2).map(s=>s[0]?.toUpperCase()).join("") || "•";
  return (
    <div className="w-6 h-6 rounded-full bg-white/10 border border-white/15 flex items-center justify-center text-xs">
      {txt}
    </div>
  );
}

/** Suchbare Combobox ohne externe Lib */
function UserSelect({ users, value, onChange, placeholder = "— auswählen —" }) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const btnRef = useRef(null);
  const popRef = useRef(null);
  const [hi, setHi] = useState(0);

  const options = useMemo(() => {
    const needle = q.trim().toLowerCase();
    const list = users || [];
    if (!needle) return list;
    return list.filter(u => {
      const s = `${u.alias || ""} ${u.name || ""} ${u.email || ""}`.toLowerCase();
      return s.includes(needle);
    });
  }, [users, q]);

  const selected = useMemo(() => (users || []).find(u => u.id === value), [users, value]);

  useEffect(() => {
    function onDoc(e) {
      if (!open) return;
      if (
        popRef.current && popRef.current.contains(e.target)
      ) return;
      if (
        btnRef.current && btnRef.current.contains(e.target)
      ) return;
      setOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  function onKey(e) {
    if (!open) return;
    if (e.key === "ArrowDown") {
      e.preventDefault(); setHi((i) => Math.min(i + 1, Math.max(0, options.length - 1)));
    } else if (e.key === "ArrowUp") {
      e.preventDefault(); setHi((i) => Math.max(i - 1, 0));
    } else if (e.key === "Enter") {
      e.preventDefault();
      const pick = options[hi];
      if (pick) { onChange(pick.id); setOpen(false); }
    } else if (e.key === "Escape") {
      e.preventDefault(); setOpen(false);
    }
  }

  return (
    <div className="relative" onKeyDown={onKey}>
      <button
        type="button"
        ref={btnRef}
        onClick={() => setOpen(o => !o)}
        className="w-full bg-black/40 text-white rounded-xl border border-white/20 px-3 py-2 text-left flex items-center justify-between hover:bg-white/5"
        aria-haspopup="listbox"
        aria-expanded={open}
      >
        <span className="flex items-center gap-2">
          {selected ? <Initials label={selected.alias || selected.name || selected.email} /> : <div className="w-6 h-6" />}
          <span className={selected ? "" : "text-white/50"}>
            {selected ? (selected.alias || selected.name || selected.email) : placeholder}
          </span>
        </span>
        <span className="text-white/50">▾</span>
      </button>

      {open && (
        <div
          ref={popRef}
          className="absolute z-20 mt-2 w-full rounded-xl border border-white/15 bg-black/80 backdrop-blur p-2 shadow-2xl"
        >
          <input
            autoFocus
            value={q}
            onChange={(e) => { setQ(e.target.value); setHi(0); }}
            placeholder="Suchen…"
            className="w-full mb-2 bg-black/40 text-white rounded-lg border border-white/20 px-3 py-2"
          />
          <ul role="listbox" className="max-h-56 overflow-auto">
            {options.map((u, idx) => (
              <li
                key={u.id}
                role="option"
                aria-selected={u.id === value}
                onMouseEnter={() => setHi(idx)}
                onMouseDown={(e) => { e.preventDefault(); onChange(u.id); setOpen(false); }}
                className={`px-2 py-2 rounded-lg cursor-pointer flex items-center gap-2 ${
                  idx === hi ? "bg-white/10" : "hover:bg-white/5"
                }`}
              >
                <Initials label={u.alias || u.name || u.email} />
                <div className="min-w-0">
                  <div className="truncate">{u.alias || u.name || u.email}</div>
                  <div className="text-xs text-white/50 truncate">{u.email || ""}</div>
                </div>
              </li>
            ))}
            {!options.length && <li className="px-2 py-2 text-white/60">Keine Treffer</li>}
          </ul>
        </div>
      )}
    </div>
  );
}




function StatusSelect({ value, onChange }) {
  const [open, setOpen] = useState(false);
  const btnRef = useRef(null);
  const popRef = useRef(null);

  const OPTIONS = [
    { value: "",          label: "alle" },
    { value: "pending",   label: "ausstehend" },
    { value: "confirmed", label: "bestätigt" },
    { value: "rejected",  label: "abgelehnt" },
  ];

  useEffect(() => {
    function onDoc(e) {
      if (!open) return;
      if (popRef.current?.contains(e.target)) return;
      if (btnRef.current?.contains(e.target)) return;
      setOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  const current = OPTIONS.find(o => o.value === value) || OPTIONS[0];

  return (
    <div className="relative">
      <button
        type="button"
        ref={btnRef}
        onClick={() => setOpen(o => !o)}
        className="min-w-[160px] bg-black/40 text-white rounded-xl border border-white/20 px-3 py-2 text-left flex items-center justify-between hover:bg-white/5"
      >
        <span>{current.label}</span>
        <span className="text-white/60">▾</span>
      </button>
      {open && (
        <div
          ref={popRef}
          className="absolute z-20 mt-2 w-full rounded-xl border border-white/15 bg-black/80 backdrop-blur p-1 shadow-2xl"
        >
          {OPTIONS.map(opt => (
            <button
              key={opt.value}
              type="button"
              onClick={() => { onChange(opt.value); setOpen(false); }}
              className={`w-full text-left px-3 py-2 rounded-lg ${
                value === opt.value ? "bg-white/15 text-white" : "text-white/80 hover:bg-white/10"
              }`}
            >
              {opt.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}


export default function AdminTransactionsPage() {
  // PayPal-Settings (jetzt legal innerhalb der Component)
  const [ppOpen, setPpOpen] = useState(false);
  const [ppMe, setPpMe] = useState("");
  const [ppReceiver, setPpReceiver] = useState("");
  const [ppSaving, setPpSaving] = useState(false);
  useEffect(() => {
    (async () => {
      try {
        const cfg = await getPaypalSettings();
        setPpMe(cfg?.paypal_me || "");
        setPpReceiver(cfg?.paypal_receiver || "");
      } catch {}
    })();
  }, []);
  async function savePaypal() {
    setPpSaving(true);
    try { await updatePaypalSettings({ paypal_me: ppMe, paypal_receiver: ppReceiver }); }
    finally { setPpSaving(false); }
  }

  // Daten
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [err,   setErr] = useState(null);
  // Nutzerliste (max 200)
  const [users, setUsers] = useState([]);

  // Filter
  const STATUS_OPTS = [
  { value: "", label: "Alle" },
  { value: "pending", label: "pending" },
  { value: "confirmed", label: "confirmed" },
  { value: "rejected", label: "rejected" },
];

const [filterUserId, setFilterUserId] = useState(null); // Nutzer-Filter (Combobox)
const [statusFilter, setStatusFilter] = useState(""); // "", "pending", "confirmed", "rejected"



  // Formular Neu
  const [form, setForm] = useState({ user_id: null, amount_eur: "", note: "" });
  const [submitting, setSubmitting] = useState(false);

  const usersById = useMemo(() => {
    const m = new Map();
    users.forEach(u => m.set(u.id, u));
    return m;
  }, [users]);

  async function loadAll() {
    setLoading(true);
    setErr(null);
    try {
      const [tx, us] = await Promise.all([
        listTopupsAdmin({
          limit: 200,
          offset: 0,
          status_filter: statusFilter || undefined,
          user_id: filterUserId || undefined,
        }),
        getUsersLite({ limit: 200, offset: 0 }),
      ]);
  
      setRows(Array.isArray(tx) ? tx : (tx.items || []));
      setUsers(Array.isArray(us) ? us : (us.items || []));
    } catch (e) {
      setErr(e?.message || "Fehler beim Laden");
    } finally {
      setLoading(false);
    }
  }
  
  useEffect(() => { loadAll(); /* eslint-disable-next-line */ }, [statusFilter, filterUserId]);

  async function onCreate(e) {
    e.preventDefault();
    const uid = Number(form.user_id);
    const eur = String(form.amount_eur ?? "").replace(",", ".");
    const cents = Math.round(Number(eur) * 100);
    if (!uid || !Number.isFinite(cents) || cents <= 0) return;

    setSubmitting(true);
    try {
      const created = await createTopupAdmin({ user_id: uid, amount_cents: cents, note: form.note || "" });
      setRows(prev => [created, ...prev]);
      setForm({ user_id: null, amount_eur: "", note: "" });
    } catch (e) {
      alert(e?.message || "Top-up konnte nicht erstellt werden.");
    } finally {
      setSubmitting(false);
    }
  }

  async function onApprove(id) {
    try {
      await patchTopupStatus(id, "confirmed");
      setRows(prev => prev.map(r => (r.id === id ? { ...r, status: "confirmed" } : r)));
    } catch (e) {
      alert(e?.message || "Bestätigen fehlgeschlagen.");
    }
  }
  async function onReject(id) {
    try {
      await patchTopupStatus(id, "rejected");
      setRows(prev => prev.map(r => (r.id === id ? { ...r, status: "rejected" } : r)));
    } catch (e) {
      alert(e?.message || "Ablehnen fehlgeschlagen.");
    }
  }

  return (
    <div className="space-y-6">
      {/* Formular Neu – ausgeblendet */}
          {SHOW_CREATE && (
          <form onSubmit={onCreate} className="rounded-2xl bg-white/5 border border-cyan-400/20 p-5">
          <h2 className="text-white/90 font-semibold mb-4">Neue Aufladung / Admin-Transaktion</h2>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
            <label className="block">
              <div className="text-xs text-white/60 mb-1">Nutzer</div>
              <UserSelect
                users={users}
                value={form.user_id}
                onChange={(id) => setForm(f => ({ ...f, user_id: id }))}
                placeholder="Nutzer wählen…"
              />
            </label>

          <label className="block">
            <div className="text-xs text-white/60 mb-1">Betrag (€)</div>
            <input
              type="number" step="0.50" inputMode="decimal" placeholder="  10,00"
              className="w-full bg-black/40 text-white rounded-xl border border-white/20 px-3 py-2"
              value={form.amount_eur}
              onChange={(e) => setForm(f => ({ ...f, amount_eur: e.target.value }))}
              required
            />
          </label>

          <label className="block md:col-span-2">
            <div className="text-xs text-white/60 mb-1">Notiz</div>
            <input
              className="w-full bg-black/40 text-white rounded-xl border border-white/20 px-3 py-2"
              placeholder="optional"
              value={form.note}
              onChange={(e) => setForm(f => ({ ...f, note: e.target.value }))}
            />
          </label>
        </div>
    
        <div className="mt-4">
          <button
            type="submit" disabled={submitting || !form.user_id}
            className="px-4 py-2 rounded-xl font-semibold bg-emerald-600/80 hover:bg-emerald-600 text-white shadow disabled:opacity-60"
          >
            Anlegen
          </button>
        </div>
      </form>
  )}

      {/* PayPal-Einstellungen */}
    <div className="rounded-2xl bg-white/5 border border-cyan-400/20 p-5">
      <button type="button"
        onClick={() => setPpOpen(o=>!o)}
        className="w-full flex items-center justify-between text-left">
        <h2 className="text-white/90 font-semibold">PayPal-Einstellungen</h2>
        <span className="text-white/60">{ppOpen ? "▴" : "▾"}</span>
      </button>
      {ppOpen && (
        <div className="mt-4 grid gap-3 md:grid-cols-3">
          <label className="block">
            <div className="text-xs text-white/60 mb-1">PayPal.me Handle (optional)</div>
            <input value={ppMe} onChange={e=>setPpMe(e.target.value)}
              className="w-full bg-black/40 text-white rounded-xl border border-white/20 px-3 py-2"
              placeholder="z. B. Getraenkewart" />
          </label>
          <label className="block md:col-span-2">
            <div className="text-xs text-white/60 mb-1">Geschäfts-E-Mail für Webscr/IPN</div>
            <input value={ppReceiver} onChange={e=>setPpReceiver(e.target.value)}
              className="w-full bg-black/40 text-white rounded-xl border border-white/20 px-3 py-2"
              placeholder="kasse@example.org" />
          </label>
          <div className="md:col-span-3">
            <button onClick={savePaypal} disabled={ppSaving}
              className="px-4 py-2 rounded-xl font-semibold bg-emerald-600/80 hover:bg-emerald-600 text-white shadow disabled:opacity-60">
              Speichern
            </button>
          </div>
        </div>
      )}
    </div>


      {/* Tabelle */}
      <div className="rounded-2xl bg-white/5 border border-cyan-400/20 p-5">
      <div className="flex items-center justify-between mb-3">
        <h2 className="text-white/90 font-semibold">Alle Transaktionen </h2>
        
        <div className="flex items-center gap-3">
          {/* Schöner Status-Filter */}
          <StatusSelect value={statusFilter} onChange={setStatusFilter} />
        
          {/* Nutzer-Filter (schöne Combobox), rechts vom Status-Filter */}
          <div className="w-64">
            <UserSelect
              users={users}
              value={filterUserId}
              onChange={setFilterUserId}
              placeholder="Nutzer filtern…"
            />
          </div>
        
          <button
            onClick={loadAll}
            className="text-sm px-3 py-2 rounded-xl border border-white/20 text-white/80 hover:bg-white/10"
          >
            Aktualisieren
          </button>
        </div>
      </div>
        

        {loading ? (
          <div className="text-white/70">Lade…</div>
        ) : err ? (
          <div className="text-rose-300 whitespace-pre-wrap">{String(err)}</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="min-w-full text-sm text-white/80">
              <thead className="text-white/60">
                <tr>
                  <th className="text-left py-2 pr-4">ID</th>
                  <th className="text-left py-2 pr-4">Zeit</th>
                  <th className="text-left py-2 pr-4">Nutzer</th>
                  <th className="text-left py-2 pr-4">Betrag (€)</th>
                  <th className="text-left py-2 pr-4">Status</th>
                  <th className="text-left py-2 pr-4">Notiz</th>
                  <th className="text-left py-2 pr-4">Aktionen</th>
                </tr>
              </thead>
              <tbody>
                {rows.map(r => {
                  const u = usersById.get(r.user_id);
                  const canAct = String(r.status) === "pending";
                  const ts = r.created_at ? new Date(String(r.created_at).replace(" ", "T")) : null;
                  return (
                    <tr key={r.id} className="border-t border-white/10">
                      <td className="py-2 pr-4 font-mono">{r.id}</td>
                      <td className="py-2 pr-4 font-mono">{ts ? fmtDT.format(ts) : "—"}</td>
                      <td className="py-2 pr-4">{u?.name || u?.alias || u?.email || r.user_id}</td>
                      <td className="py-2 pr-4 font-mono">{fmt.format(euro(r.amount_cents))}</td>
                      <td className="py-2 pr-4"><Pill status={String(r.status)} /></td>
                      <td className="py-2 pr-4 font-mono break-all">{toText(r.note)}</td>
                      <td className="py-2 pr-4">
                        <div className="flex items-center gap-2">
                          <button
                            disabled={!canAct}
                            onClick={() => onApprove(r.id)}
                            className="px-3 py-1 rounded-lg text-xs bg-emerald-600/80 hover:bg-emerald-600 text-white disabled:opacity-40"
                          >
                            Bestätigen
                          </button>
                          <button
                            disabled={!canAct}
                            onClick={() => onReject(r.id)}
                            className="px-3 py-1 rounded-lg text-xs bg-rose-600/80 hover:bg-rose-600 text-white disabled:opacity-40"
                          >
                            Ablehnen
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
                {!rows.length && (
                  <tr>
                    <td colSpan={7} className="py-6 text-center text-white/60">Keine Einträge.</td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
