import React, { Suspense, lazy } from "react";
import { NavLink } from "react-router-dom";
import LoadingComponent from "../common/LoadingComponent";
import history from "../history";
import MenuItem from "../screens/Console/Menu/MenuItem";

// 对 lazy 包装一层，在私有部署环境中没有模块联邦，直接返回 null
const _lazy: typeof lazy = (factory) => {
  if (process.env.REACT_APP_SATURN_ENV === "private") {
    return null;
  }
  return lazy(factory);
};

const RemoteSaturnTenant = _lazy(() => import("saturn_tenant/App"));
const RemoteSaturnTenantFullscreen = _lazy(
  () => import("saturn_tenant/AppFullscreen")
);
const RemoteMenuContainer = _lazy(() => import("saturn_tenant/MenuContainer"));

/** 在 Layout 下展示的内容 */
export function SaturnTenant() {
  return (
    <Suspense fallback={<LoadingComponent />}>
      <RemoteSaturnTenant history={history} />
    </Suspense>
  );
}

/** 全屏展示的内容 */
export function SaturnTenantFullscreen() {
  return (
    <Suspense fallback={<LoadingComponent />}>
      <RemoteSaturnTenantFullscreen history={history} />
    </Suspense>
  );
}

/** 全屏展示的内容 */
export function SaturnTenantMenuContainer({
  children,
  isOpen,
  groupState,
}: {
  children: React.ReactNode;
  isOpen: boolean;
  groupState: {
    openGroup: string;
    setOpenGroup: React.Dispatch<React.SetStateAction<string>>;
    expandedGroup: string;
    setExpandedGroup: React.Dispatch<React.SetStateAction<string>>;
  };
}) {
  // 这里比较特殊，因为是 hack 不能直接返回 null 了
  if (process.env.REACT_APP_SATURN_ENV === "private") {
    return <>{children}</>;
  }
  return (
    <Suspense fallback={<LoadingComponent />}>
      <RemoteMenuContainer context={{ MenuItem, NavLink, isOpen, groupState }}>
        {children}
      </RemoteMenuContainer>
    </Suspense>
  );
}

export function runInject() {
  if (process.env.REACT_APP_SATURN_ENV !== "private") {
    import("saturn_tenant/run");
  }
}

// /** 加载一个函数方法 */
// export function useSaturnConsoleMenu() {
//   const [menu, setMenu] = useState([]);

//   // useEffect(() => {
//   //   import("saturn_tenant/consoleMenu")
//   //     .then((res) => {
//   //       const createMenu = res.default;
//   //       createMenu(NavLink).then((menu) => {
//   //         setMenu(menu);
//   //       });
//   //     })
//   //     .catch((e) => {
//   //       console.error(e);
//   //     });
//   // }, []);

//   return menu;
// }
