import React, { useEffect, useState, Suspense, useMemo } from "react";;
import { NavLink, Outlet, useNavigate } from "react-router-dom";
import {
  FiCpu,
  FiHome,
  FiUsers,
  FiPackage,
  FiTruck,
  FiBarChart2,
  FiSettings,
  FiLogOut,
  FiActivity,
  FiCalendar,
  FiCreditCard,
  FiList,
} from "react-icons/fi";
import { logout, getCapabilities, API_BASE } from "../api";

/* ---------- Hintergrund ---------- */
function BackgroundFX({ children }) {
  return (
    <div className="relative min-h-screen">
      <div
        className="absolute inset-0 -z-20"
        style={{
          background:
            "radial-gradient(1200px 600px at 70% 0%, rgba(0,120,255,0.08), transparent 60%)," +
            "radial-gradient(1000px 600px at 30% 100%, rgba(0,255,170,0.06), transparent 60%)," +
            "linear-gradient(180deg, #0a0a0a 0%, #0b1020 100%)",
        }}
      />
      <div
        className="pointer-events-none absolute inset-0 -z-10 opacity-[0.06]"
        style={{
          backgroundImage:
            "linear-gradient(transparent 24px, rgba(255,255,255,0.05) 25px), linear-gradient(90deg, transparent 24px, rgba(255,255,255,0.05) 25px)",
          backgroundSize: "25px 25px",
          maskImage:
            "radial-gradient(70% 60% at 50% 50%, black 60%, transparent 100%)",
        }}
      />
      {children}
    </div>
  );
}

/* ---------- Navigation ---------- */
const NAV_ALL = [
  { cap: "dashboard",        to: "/management",              label: "Dashboard",     icon: FiHome,      end: true },
  { cap: "my-bookings",      to: "/management/bookings",     label: "Buchungen",     icon: FiCalendar },
  { cap: "my-transactions",  to: "/management/transaction",  label: "Transaktion",   icon: FiCreditCard },
  { cap: "system-config",    to: "/management/settings",     label: "Einstellungen", icon: FiSettings },
  { cap: "users",            to: "/management/users",        label: "Nutzer",        icon: FiUsers },
  { cap: "products",         to: "/management/products",     label: "Produkte",      icon: FiPackage },
  { cap: "deliveries",       to: "/management/deliveries",   label: "Lieferungen",   icon: FiTruck },
  { cap: "stats-advanced",   to: "/management/stats",        label: "Statistiken",   icon: FiBarChart2 },
  { cap: "transactions",     to: "/management/transactions", label: "Transaktionen", icon: FiList },
  { cap: "audit-logs",       to: "/management/logs",         label: "Logs",          icon: FiActivity },
];

// Route-Chunks für Prefetch
const prefetchMap = {
  "/management":             () => import("./pages/DashboardPage"),
  "/management/bookings":    () => import("./pages/BookingsPage"),
  "/management/transaction": () => import("./pages/TransactionPage"),
  "/management/transactions":() => import("./pages/AdminTransactionsPage"),
  "/management/users":       () => import("./pages/UsersPage"),
  "/management/products":    () => import("./pages/ProductsPage"),
  "/management/deliveries":  () => import("./pages/DeliveriesPage"),
  "/management/stats":       () => import("./pages/StatsPage"),
  "/management/logs":        () => import("./pages/LogsPage"),
  "/management/settings":    () => import("./pages/SettingsPage"),
};

/* ---------- Sidebar ---------- */
function Sidebar({ capabilities, collapsed, onToggle }) {
  const navItems = NAV_ALL.filter((item) => capabilities.includes(item.cap));

  return (
    <aside
      className={[
        "h-screen sticky top-0 bg-white/5 backdrop-blur-md border-r border-white/10 px-3 py-4 transition-all duration-200",
        collapsed ? "w-[72px]" : "w-[260px]",
      ].join(" ")}
      aria-label="Seitenleiste"
      aria-expanded={!collapsed}
    >
      <div className="flex items-center gap-2 px-1 mb-6">
        <button
          type="button"
          onClick={onToggle}
          className={[
            "p-2 rounded-xl border transition",
            "border-cyan-400/30 bg-cyan-500/10 hover:bg-cyan-500/20",
            "focus:outline-none focus:ring-2 focus:ring-cyan-400/40",
          ].join(" ")}
          title={collapsed ? "Sidebar ausklappen" : "Sidebar einklappen"}
          aria-label={collapsed ? "Sidebar ausklappen" : "Sidebar einklappen"}
        >
          <FiCpu className="text-cyan-300" />
        </button>

        {!collapsed && (
          <div className="leading-tight select-none">
            <div className="text-white font-semibold">Bacchus</div>
            <div className="text-white/50 text-xs font-mono">management</div>
          </div>
        )}
      </div>

      <nav className="space-y-1">
        {navItems.map(({ to, label, icon: Icon, end }) => (
          <NavLink
            key={to}
            to={to}
            onMouseEnter={() => prefetchMap[to]?.()}
            end={end}
            className={({ isActive }) =>
              [
                "flex items-center gap-3 px-3 py-2 rounded-xl transition group",
                "hover:bg-white/10",
                isActive
                  ? "bg-cyan-500/15 text-cyan-200 border border-cyan-400/30"
                  : "text-white/70 border border-transparent",
                collapsed ? "justify-center" : "",
              ].join(" ")
            }
            title={label}
          >
            <Icon className="shrink-0" />
            {!collapsed && <span className="text-sm">{label}</span>}
          </NavLink>
        ))}
      </nav>

      {/* kleiner Status unten */}
      <div className={["mt-8", collapsed ? "px-0" : "px-2"].join(" ")}>
        <div
          className={[
            "rounded-2xl bg-white/5 backdrop-blur-md",
            "border border-cyan-400/20",
            "shadow-[0_0_0_1px_rgba(34,211,238,0.05)]",
            "p-3",
          ].join(" ")}
        >
          {!collapsed && (
            <div className="text-xs text-white/60 mb-1 font-mono">
              …Connecting to Bacchus DB…
            </div>
          )}
          <div className="h-1.5 w-full bg-white/10 rounded overflow-hidden">
            <div className="h-full w-1/3 bg-cyan-400/50 animate-pulse" />
          </div>
        </div>
      </div>
    </aside>
  );
}

/* ---------- Topbar (mit Avatar aus Backend) ---------- */
const DEFAULT_AVATAR = "/avatar-default.png";

function Topbar({ user, onLogout }) {
  const avatarSrc = useMemo(() => {
    const raw = (user?.avatar_url || "").trim();
    if (!raw) return DEFAULT_AVATAR;                          // kein Avatar gesetzt
    if (/^(https?:|data:|blob:|\/\/)/i.test(raw)) return raw; // absolute/data/blob
    // relative Backend-URL präfixen
    return `${API_BASE}${raw.startsWith("/") ? raw : `/${raw}`}`;
  }, [user?.avatar_url, API_BASE]);

  return (
    <div
      className="h-16 flex items-center justify-between px-4
                 border-b border-white/10 bg-white/5 backdrop-blur-md"
    >
      <div className="text-white/60 text-sm select-none"></div>

      <div className="flex items-center gap-4">
        <div
          className="flex items-center gap-3 px-3 py-1.5 rounded-xl bg-white/5 border border-white/10"
          title="current user"
        >
          <img
            src={avatarSrc}
            alt={user?.name || user?.alias || user?.email || "Avatar"}
            onError={(e) => { e.currentTarget.onerror = null; e.currentTarget.src = DEFAULT_AVATAR; }}
            referrerPolicy="no-referrer"
            loading="lazy"
            decoding="async"
            className="w-8 h-8 rounded-full object-cover ring-1 ring-cyan-400/30"
          />
          <div className="leading-tight">
            <div className="text-white text-sm font-semibold">
              {user?.name ?? "Admin"}
            </div>
            <div className="text-white/50 text-xs font-mono">
              {(user?.role ?? "manager").toString()}
            </div>
          </div>
        </div>

        <button
          onClick={onLogout}
          className="inline-flex items-center gap-2 px-3 py-2 rounded-xl
                     bg-red-500/15 text-red-200 border border-red-400/30
                     hover:bg-red-500/25 transition"
          title="Logout"
        >
          <FiLogOut />
          <span className="text-sm">Logout</span>
        </button>
      </div>
    </div>
  );
}


/* ---------- Layout-Hülle ---------- */
export default function ManagementLayout({ currentUser }) {
  const navigate = useNavigate();
  const [capabilities, setCapabilities] = useState([]);
  const [loading, setLoading] = useState(true);
  const [collapsed, setCollapsed] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const data = await getCapabilities();
        setCapabilities(Array.isArray(data.capabilities) ? data.capabilities : []);
      } catch {
        setCapabilities(["dashboard", "profile", "my-bookings"]);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const handleLogout = async () => {
    try {
      await logout();
    } catch {
      /* ignore */
    } finally {
      navigate("/management-login", { replace: true });
    }
  };

  if (loading) {
    return <div className="p-6 text-white">Lade Managementbereich …</div>;
  }

  return (
    <BackgroundFX>
      <div className="flex">
        <Sidebar
          capabilities={capabilities}
          collapsed={collapsed}
          onToggle={() => setCollapsed((v) => !v)}
        />
        <main className="flex-1 min-h-screen">
          <Topbar user={currentUser} onLogout={handleLogout} />
          <section
            className="p-6 transition-all"
            style={{ contentVisibility: "auto", containIntrinsicSize: "800px" }}
          >
            <Suspense fallback={<div className="text-white/80 p-6">Lade…</div>}>
              <Outlet />
            </Suspense>
          </section>
        </main>
      </div>
    </BackgroundFX>
  );
}
