import React, { useEffect, useState } from "react";
import { getCapabilities, getStatsSummary } from "../../api";
import { FiCreditCard, FiTrendingUp, FiDatabase, FiZap, FiAlertTriangle } from "react-icons/fi";

function Panel({ title, icon: Icon, children, accent = "cyan" }) {
  const accentClasses =
    accent === "red"
      ? "border-red-400/25 shadow-[0_0_0_1px_rgba(248,113,113,0.06)]"
      : accent === "amber"
      ? "border-amber-400/25 shadow-[0_0_0_1px_rgba(251,191,36,0.06)]"
      : accent === "emerald"
      ? "border-emerald-400/25 shadow-[0_0_0_1px_rgba(16,185,129,0.06)]"
      : "border-cyan-400/25 shadow-[0_0_0_1px_rgba(34,211,238,0.06)]";

  return (
    <div className={`rounded-2xl bg-white/5 backdrop-blur-md border ${accentClasses} p-5`}>
      <div className="flex items-center gap-2 mb-3">
        <Icon className="text-white/80" />
        <h2 className="text-white/90 font-semibold">{title}</h2>
      </div>
      {children}
    </div>
  );
}

export default function DashboardPage() {
  const [caps, setCaps] = useState([]);
  const [summary, setSummary] = useState(null);
  const [statsDenied, setStatsDenied] = useState(false);
  const [err, setErr] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let alive = true;
    (async () => {
      try {
        const { capabilities } = await getCapabilities();
        if (!alive) return;
        const c = Array.isArray(capabilities) ? capabilities : [];
        setCaps(c);

        if (c.includes("stats-advanced")) {
          try {
            const s = await getStatsSummary();
            if (!alive) return;
            setSummary(s || null);
            setStatsDenied(false);
          } catch (e) {
            // 403 oder andere Fehler -> degradiert anzeigen
            if (e?.response?.status === 403 || e?.status === 403) {
              setStatsDenied(true);
              setSummary(null);
            } else {
              // kein harter Crash – wir degradieren
              setSummary(null);
            }
          }
        }
      } catch (e) {
        if (alive) setErr(e);
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => {
      alive = false;
    };
  }, []);

  // --- ab hier keine neuen Hooks mehr ---

  // Ableitungen robust ohne useMemo/useCallback
  const balanceCents = summary?.my_balance_cents;
  const balanceText =
    typeof balanceCents === "number" ? (balanceCents / 100).toFixed(2) + " €" : "—";
  const balanceAccent =
    typeof balanceCents === "number"
      ? balanceCents < 0
        ? "red"
        : balanceCents < 500
        ? "amber"
        : "emerald"
      : "cyan";

  const stock =
    summary?.stock_overview && typeof summary.stock_overview === "object"
      ? summary.stock_overview
      : null;

  const sys = {
    users: summary?.num_users ?? "—",
    products: summary?.num_products ?? "—",
    bookings: summary?.num_bookings ?? "—",
    revenue:
      typeof summary?.total_revenue_cents === "number"
        ? (summary.total_revenue_cents / 100).toFixed(2) + " €"
        : "—",
  };

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

  return (
    <div className="grid xl:grid-cols-2 gap-6">
      {/* Kontostand */}
      <Panel title="Kontostand" icon={FiCreditCard} accent={balanceAccent}>
        <div className="text-4xl text-white font-mono tracking-tight">
          {balanceText}
          {balanceText !== "—" && (
            <span className="ml-2 text-white/40 text-lg align-middle"></span>
          )}
        </div>
        {balanceText === "—" && (
          <div className="text-white/60 text-sm mt-2">
             Kontostand verbinden 
            <span className="hidden sm:inline"> </span>
            <span className="font-mono">/stats/summary</span>).
          </div>
        )}
      </Panel>

      {/* Aufladen */}
      <Panel title="Aufladen" icon={FiZap}>
        <div className="text-white/70 text-sm mb-3">
          Guthaben erhöhen. Paypal link verbinden diesdas...
        </div>
        <div className="flex flex-wrap gap-2">
          <a
            href="/management/transaction"
            className="inline-flex items-center gap-2 px-4 py-2 rounded-xl
                       bg-emerald-500/20 text-emerald-200 border border-emerald-400/30
                       hover:bg-emerald-500/30 transition"
          >
            <FiZap />
            <span>Jetzt aufladen</span>
          </a>
        </div>
      </Panel>

      {/* Getränkelage */}
      <Panel title="Getränkelage" icon={FiTrendingUp}>
        {stock ? (
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            {Object.entries(stock).map(([k, v]) => {
              const pct = Math.max(0, Math.min(1, Number(v) || 0));
              const barClass =
                pct < 0.25 ? "bg-red-400/60" : pct < 0.5 ? "bg-amber-400/60" : "bg-emerald-400/60";
              return (
                <div key={k} className="text-white/80 text-sm">
                  <div className="mb-1 capitalize">{k}</div>
                  <div className="h-2 w-full bg-white/10 rounded">
                    <div
                      className={`h-full ${barClass} rounded`}
                      style={{ width: `${Math.round(pct * 100)}%` }}
                      aria-valuemin={0}
                      aria-valuemax={100}
                      aria-valuenow={Math.round(pct * 100)}
                      role="progressbar"
                    />
                  </div>
                  <div className="text-white/50 text-xs mt-1 font-mono">
                    {Math.round(pct * 100)}%
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <div className="text-white/60 text-sm">
            Gut gefüllt nächste Lieferungen am: 30.01.26
            <span className="hidden sm:inline"> </span>
          </div>
        )}
      </Panel>

      {/* Systemstatus */}
      <Panel title="Systemstatus" icon={FiDatabase}>
        <div className="text-white/80 text-sm space-y-1 font-mono leading-6">
          <div>Users: {sys.users}</div>
          <div>Products: {sys.products}</div>
          <div>Bookings: {sys.bookings}</div>
          <div>Revenue: {sys.revenue}</div>
        </div>

        {!caps.includes("stats-advanced") && (
          <div className="text-white/60 text-xs mt-3">
            Hinweis: Erweiterte Statistiken sind nicht freigeschaltet (<code className="font-mono">stats-advanced</code>).
          </div>
        )}
        {caps.includes("stats-advanced") && statsDenied && (
          <div className="text-amber-200/90 text-xs mt-3">
            Zugriff verweigert (403). Prüfe Auth/Rolle/CSRF des Endpoints <code className="font-mono">/stats/summary</code>.
          </div>
        )}
      </Panel>
    

    {/* Leer */}
      <Panel title="Leer :(" icon={FiAlertTriangle}>
        <div className="text-white/70 text-sm mb-3">
          Hier leere Produkte auflisten
        </div>
        <div className="flex flex-wrap gap-2">
          <a
            
            className="inline-flex items-center gap-2 px-4 py-2 rounded-xl
                       bg-emerald-500/20 text-emerald-200 border border-emerald-400/30
                       hover:bg-emerald-500/30 transition"
          >
          </a>
        </div>
      </Panel>
      </div>
  );
}
