import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { ContemberClient } from "@contember/react-client";
import { Providers, Button, Icon, SpinnerOverlay, ErrorList, Stack } from "@contember/ui";
import { useState, useEffect, useMemo } from "react";
import { MiscPageLayout } from "../MiscPageLayout.js";
import { Pages } from "../pageRouting/Pages.js";
import { CreateResetPasswordRequestForm } from "../../tenant/components/password/CreateResetPasswordRequestForm.js";
import { FillResetPasswordTokenForm } from "../../tenant/components/password/FillResetPasswordTokenForm.js";
import { ResetPasswordForm } from "../../tenant/components/password/ResetPasswordForm.js";
import { useRedirectToBacklink, useRedirectToBacklinkCallback } from "../../tenant/components/person/useRedirectToBacklink.js";
import { ProjectListButtons } from "../Project/ProjectList.js";
import { useIDPAutoInit } from "../../tenant/components/idp/useIDPAutoInit.js";
import { useResponseHandlerFeedback } from "../../tenant/components/idp/IDPResponseHandler.js";
import { Login } from "../../tenant/components/person/Login.js";
import { IDPInitButton } from "../../tenant/components/idp/IDPInitButton.js";
import { RoutingContext, RequestProvider, Page } from "@contember/react-routing";
import { IdentityProvider } from "../Identity/IdentityProvider.js";
import { Link } from "../../routing/Link.js";
import { useLogout, useIdentity } from "@contember/react-identity";
const indexPageName = "index";
const resetRequestPageName = "resetRequest";
const redirectOnSuccessPageName = "resetRequestSuccess";
const passwordResetPageName = "passwordReset";
const LoginEntrypoint = (props) => {
  const routing = {
    basePath: props.basePath ?? "/",
    routes: {},
    defaultDimensions: {},
    pageInQuery: true
  };
  return /* @__PURE__ */ jsx(
    ContemberClient,
    {
      apiBaseUrl: props.apiBaseUrl,
      sessionToken: props.sessionToken,
      loginToken: props.loginToken,
      children: /* @__PURE__ */ jsx(RoutingContext.Provider, { value: routing, children: /* @__PURE__ */ jsx(RequestProvider, { children: /* @__PURE__ */ jsx(Providers, { children: /* @__PURE__ */ jsxs(Pages, { children: [
        /* @__PURE__ */ jsx(Page, { name: indexPageName, children: /* @__PURE__ */ jsx(IdentityProvider, { allowUnauthenticated: true, children: /* @__PURE__ */ jsx(
          LoginEntrypointIndex,
          {
            projects: props.projects,
            formatProjectUrl: props.formatProjectUrl,
            identityProviders: props.identityProviders,
            heading: props.heading,
            projectsPageActions: props.projectsPageActions,
            collapsedEmailLogin: props.collapsedEmailLogin
          }
        ) }) }),
        /* @__PURE__ */ jsx(Page, { name: resetRequestPageName, children: /* @__PURE__ */ jsx(MiscPageLayout, { heading: "Password reset", actions: /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(Link, { to: indexPageName, children: "← Back to login" }) }), children: /* @__PURE__ */ jsx(CreateResetPasswordRequestForm, { redirectOnSuccess: redirectOnSuccessPageName }) }) }),
        /* @__PURE__ */ jsx(Page, { name: redirectOnSuccessPageName, children: /* @__PURE__ */ jsxs(MiscPageLayout, { heading: "Password reset", actions: /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(Link, { to: indexPageName, children: "← Back to login" }) }), children: [
          /* @__PURE__ */ jsx("p", { children: "Password reset request has been successfully created. Please check your inbox for the instructions." }),
          /* @__PURE__ */ jsx("p", { children: "Please follow the link in e-mail or copy the reset token here:" }),
          /* @__PURE__ */ jsx(FillResetPasswordTokenForm, { resetLink: `${passwordResetPageName}(token: $token)` })
        ] }) }),
        /* @__PURE__ */ jsx(Page, { name: passwordResetPageName, children: ({ token }) => /* @__PURE__ */ jsx(MiscPageLayout, { heading: "Set a new password", actions: /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(Link, { to: indexPageName, children: "← Back to login" }) }), children: /* @__PURE__ */ jsx(ResetPasswordForm, { token, redirectOnSuccess: indexPageName }) }) })
      ] }) }) }) })
    }
  );
};
const LoginEntrypointIndex = (props) => {
  const logout = useLogout();
  const identity = useIdentity();
  const [projectSlugs, setProjectSlugs] = useState();
  const projectsProvider = props.projects;
  useEffect(() => {
    (async () => {
      if (identity === void 0) {
        return;
      }
      setProjectSlugs(projectsProvider instanceof Function ? await projectsProvider() : projectsProvider);
    })();
  }, [identity, projectsProvider]);
  const projects = useMemo(() => {
    return identity?.projects.filter((it) => projectSlugs?.includes(it.slug));
  }, [identity?.projects, projectSlugs]);
  useRedirectToBacklink();
  if (identity === void 0) {
    return /* @__PURE__ */ jsx(MiscPageLayout, { heading: props.heading ?? "Contember Admin", children: /* @__PURE__ */ jsx(LoginContainer, { identityProviders: props.identityProviders, collapsedEmailLogin: props.collapsedEmailLogin }) });
  } else if (projects === void 0) {
    return /* @__PURE__ */ jsx(
      MiscPageLayout,
      {
        heading: "Projects",
        actions: /* @__PURE__ */ jsxs(Fragment, { children: [
          props.projectsPageActions,
          /* @__PURE__ */ jsx(Button, { onClick: () => logout(), size: "small", distinction: "seamless", children: /* @__PURE__ */ jsx(Icon, { blueprintIcon: "log-out" }) })
        ] }),
        children: "Loading projects..."
      }
    );
  } else if (projects.length === 1) {
    window.location.href = props.formatProjectUrl(projects[0]);
    return null;
  } else {
    return /* @__PURE__ */ jsx(
      MiscPageLayout,
      {
        heading: "Projects",
        actions: props.projectsPageActions,
        footerActions: /* @__PURE__ */ jsxs(Button, { onClick: () => logout(), distinction: "seamless", display: "block", children: [
          "Sign out ",
          /* @__PURE__ */ jsx(Icon, { blueprintIcon: "log-out" })
        ] }),
        children: /* @__PURE__ */ jsx(ProjectListButtons, { projects, formatProjectUrl: props.formatProjectUrl })
      }
    );
  }
};
const LoginContainer = ({ identityProviders = [], collapsedEmailLogin: initialCollapsedEmailLogin }) => {
  const [collapsedEmailLogin, setCollapsedEmailLogin] = useState(initialCollapsedEmailLogin ?? false);
  const [error, setError] = useState();
  const redirectToBacklink = useRedirectToBacklinkCallback();
  const idpAutoInit = useIDPAutoInit({ providers: identityProviders });
  const idpHandlerFeedback = useResponseHandlerFeedback({ onLogin: redirectToBacklink });
  const errors = useMemo(() => [
    ...error ? [{ message: error }] : [],
    ...idpAutoInit.type === "failed" ? [{ message: idpAutoInit.error }] : []
  ], [error, idpAutoInit]);
  if (idpHandlerFeedback !== null) {
    return idpHandlerFeedback;
  }
  if (idpAutoInit.type === "processing") {
    return /* @__PURE__ */ jsx(SpinnerOverlay, {});
  }
  const visibleIdentityProviders = identityProviders.filter((it) => !it.hidden);
  const showAlternativeLoginButtons = visibleIdentityProviders.length > 0 || collapsedEmailLogin;
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(ErrorList, { errors }),
    !collapsedEmailLogin && /* @__PURE__ */ jsx(Login, { resetLink: resetRequestPageName, onLogin: redirectToBacklink }),
    showAlternativeLoginButtons && /* @__PURE__ */ jsxs(Stack, { children: [
      visibleIdentityProviders.map((it, i) => /* @__PURE__ */ jsx(IDPInitButton, { provider: it, onError: setError }, i)),
      collapsedEmailLogin && /* @__PURE__ */ jsx(Button, { onClick: () => setCollapsedEmailLogin(false), children: "Login with email" })
    ] })
  ] });
};
export {
  LoginEntrypoint
};
//# sourceMappingURL=LoginEntrypoint.js.map
