import { useEffect, useMemo, useState } from "react";
import { matchPath, Outlet, useLocation, useNavigate } from "react-router-dom";
import { useAuth } from "@/app/auth/AuthProvider.jsx";
import { useAppScope } from "@/app/app-scope/AppScopeProvider.jsx";
import { getMenus } from "@/features/menus/api";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { useRefreshSignal } from "@/shared/hooks/useRefreshSignal.js";
import {
  fallbackNavigation,
  filterNavigationByPermission,
  findNavItemByPath,
  mapBackendMenus,
  mergeNavigationItems
} from "@/app/navigation/menu.js";
import { recordSecondLevelMenuVisit } from "@/app/navigation/menuUsage.js";
import { adminRoutes } from "@/app/router/routeConfig";
import { Header } from "./Header.jsx";
import { Sidebar } from "./Sidebar.jsx";

export function AdminLayout() {
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const location = useLocation();
  const navigate = useNavigate();
  const { can, user } = useAuth();
  const { hasAppAccess, loading: appScopeLoading } = useAppScope();
  const { refresh } = useRefreshSignal();
  const { data: backendMenus } = useAdminQuery(() => getMenus(), {
    errorMessage: "加载菜单失败",
    initialData: [],
    queryKey: ["navigation", "menus"],
    staleTime: 5 * 60 * 1000
  });
  const menus = useMemo(() => {
    const fallbackMenus = filterNavigationByPermission(fallbackNavigation, can);
    if (!backendMenus?.length) {
      return appScopeLoading || hasAppAccess ? fallbackMenus : fallbackMenus.filter((item) => item.code === "overview");
    }
    const merged = mergeNavigationItems(mapBackendMenus(backendMenus), fallbackMenus, fallbackNavigation);
    // 通用模式只保留工作台入口；App 业务菜单即使角色有权限，也不能在零 App 状态下进入。
    return appScopeLoading || hasAppAccess ? merged : merged.filter((item) => item.code === "overview");
  }, [appScopeLoading, backendMenus, can, hasAppAccess]);
  const activeNav = useMemo(() => findNavItemByPath(location.pathname, menus), [location.pathname, menus]);
  const activeRoute = useMemo(
    () => adminRoutes.find((route) => matchPath({ end: true, path: route.path }, location.pathname)),
    [location.pathname]
  );

  useEffect(() => {
    recordSecondLevelMenuVisit({ menus, pathname: location.pathname, user });
  }, [location.pathname, menus, user]);

  return (
    <div className={`app-shell ${sidebarCollapsed ? "app-shell--sidebar-collapsed" : ""}`}>
      <Header
        activeLabel={activeRoute?.label || activeNav?.label || "总览"}
        isSidebarCollapsed={sidebarCollapsed}
        menuItems={menus}
        onRefresh={refresh}
        onToggleSidebar={() => setSidebarCollapsed((current) => !current)}
      />

      <div className="body-grid">
        <Sidebar activePath={location.pathname} isCollapsed={sidebarCollapsed} items={menus} onNavigate={navigate} />

        <main className="workspace">
          <div className="page-transition" key={location.pathname}>
            <Outlet context={{ menus }} />
          </div>
        </main>
      </div>
    </div>
  );
}
