import { createElement, Fragment, useState, useEffect, useMemo, useCallback } from "react";
import { ContemberClient } from "@contember/react-client";
import { StyleProvider, ToasterProvider, Toaster, Button, Icon, ErrorList, Stack } from "@contember/ui";
import { MiscPageLayout } from "../MiscPageLayout.js";
import { Pages } from "../pageRouting/Pages.js";
import { Page } from "../pageRouting/Page.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 { useOptionalIdentity } from "../Identity/useOptionalIdentity.js";
import { ProjectListButtons } from "../Project/ProjectList.js";
import { IDPResponseHandler } from "../../tenant/components/idp/IDPResponseHandler.js";
import { Login } from "../../tenant/components/person/Login.js";
import { IDPInitButton } from "../../tenant/components/idp/IDPInitButton.js";
import { RoutingContext } from "../../routing/RoutingContext.js";
import { RequestProvider } from "../../routing/RequestContext.js";
import { IdentityProvider } from "../Identity/IdentityProvider.js";
import { Link } from "../../routing/binding/Link.js";
import { useLogout } from "../Identity/useLogout.js";
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__ */ createElement(ContemberClient, {
    apiBaseUrl: props.apiBaseUrl,
    sessionToken: props.sessionToken,
    loginToken: props.loginToken
  }, /* @__PURE__ */ createElement(StyleProvider, null, /* @__PURE__ */ createElement(ToasterProvider, null, /* @__PURE__ */ createElement(RoutingContext.Provider, {
    value: routing
  }, /* @__PURE__ */ createElement(RequestProvider, null, /* @__PURE__ */ createElement(Pages, null, /* @__PURE__ */ createElement(Page, {
    name: indexPageName
  }, /* @__PURE__ */ createElement(IdentityProvider, {
    allowUnauthenticated: true
  }, /* @__PURE__ */ createElement(LoginEntrypointIndex, {
    projects: props.projects,
    formatProjectUrl: props.formatProjectUrl,
    identityProviders: props.identityProviders,
    heading: props.heading,
    projectsPageActions: props.projectsPageActions,
    collapsedEmailLogin: props.collapsedEmailLogin
  }))), /* @__PURE__ */ createElement(Page, {
    name: resetRequestPageName
  }, /* @__PURE__ */ createElement(MiscPageLayout, {
    heading: "Password reset",
    actions: /* @__PURE__ */ createElement(Fragment, null, /* @__PURE__ */ createElement(Link, {
      to: indexPageName
    }, "\u2190 Back to login"))
  }, /* @__PURE__ */ createElement(CreateResetPasswordRequestForm, {
    redirectOnSuccess: redirectOnSuccessPageName
  }))), /* @__PURE__ */ createElement(Page, {
    name: redirectOnSuccessPageName
  }, /* @__PURE__ */ createElement(MiscPageLayout, {
    heading: "Password reset",
    actions: /* @__PURE__ */ createElement(Fragment, null, /* @__PURE__ */ createElement(Link, {
      to: indexPageName
    }, "\u2190 Back to login"))
  }, /* @__PURE__ */ createElement("p", null, "Password reset request has been successfully created. Please check your inbox for the instructions."), /* @__PURE__ */ createElement("p", null, "Please follow the link in e-mail or copy the reset token here:"), /* @__PURE__ */ createElement(FillResetPasswordTokenForm, {
    resetLink: (token) => ({ pageName: passwordResetPageName, parameters: { token } })
  }))), /* @__PURE__ */ createElement(Page, {
    name: passwordResetPageName
  }, ({ token }) => /* @__PURE__ */ createElement(MiscPageLayout, {
    heading: "Set a new password",
    actions: /* @__PURE__ */ createElement(Fragment, null, /* @__PURE__ */ createElement(Link, {
      to: indexPageName
    }, "\u2190 Back to login"))
  }, /* @__PURE__ */ createElement(ResetPasswordForm, {
    token,
    redirectOnSuccess: indexPageName
  })))))), /* @__PURE__ */ createElement(Toaster, null))));
};
const LoginEntrypointIndex = (props) => {
  const logout = useLogout();
  const identity = useOptionalIdentity();
  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]);
  if (identity === void 0) {
    return /* @__PURE__ */ createElement(MiscPageLayout, {
      heading: props.heading ?? "Contember Admin"
    }, /* @__PURE__ */ createElement(LoginContainer, {
      identityProviders: props.identityProviders,
      collapsedEmailLogin: props.collapsedEmailLogin
    }));
  } else if (projects === void 0) {
    return /* @__PURE__ */ createElement(MiscPageLayout, {
      heading: "Projects",
      actions: /* @__PURE__ */ createElement(Fragment, null, props.projectsPageActions, /* @__PURE__ */ createElement(Button, {
        onClick: () => logout(),
        size: "small",
        distinction: "seamless"
      }, /* @__PURE__ */ createElement(Icon, {
        blueprintIcon: "log-out"
      })))
    }, "Loading projects...");
  } else if (projects.length === 1) {
    window.location.href = props.formatProjectUrl(projects[0]);
    return null;
  } else {
    return /* @__PURE__ */ createElement(MiscPageLayout, {
      heading: "Projects",
      actions: props.projectsPageActions,
      footerActions: /* @__PURE__ */ createElement(Button, {
        onClick: () => logout(),
        distinction: "seamless",
        flow: "block"
      }, "Sign out ", /* @__PURE__ */ createElement(Icon, {
        blueprintIcon: "log-out"
      }))
    }, /* @__PURE__ */ createElement(ProjectListButtons, {
      projects,
      formatProjectUrl: props.formatProjectUrl
    }));
  }
};
const LoginContainer = ({ identityProviders, collapsedEmailLogin: initialCollapsedEmailLogin }) => {
  const [collapsedEmailLogin, setCollapsedEmailLogin] = useState(initialCollapsedEmailLogin ?? false);
  const [error, setError] = useState();
  const onLoginHandler = useCallback(() => {
    const params = new URLSearchParams(window.location.search);
    const backlink = params.get("backlink");
    if (backlink) {
      const resolvedBacklink = new URL(backlink, window.location.href);
      if (resolvedBacklink.origin === window.location.origin) {
        window.location.href = resolvedBacklink.toString();
      }
    }
  }, []);
  const hasOauthResponse = useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.has("state") && (params.has("code") || params.has("id_token"));
  }, []);
  if (hasOauthResponse) {
    return /* @__PURE__ */ createElement(IDPResponseHandler, {
      onLogin: onLoginHandler
    });
  }
  return /* @__PURE__ */ createElement(Fragment, null, /* @__PURE__ */ createElement(ErrorList, {
    errors: error ? [{ message: error }] : []
  }), !collapsedEmailLogin && /* @__PURE__ */ createElement(Login, {
    resetLink: resetRequestPageName,
    onLogin: onLoginHandler
  }), ((identityProviders?.length ?? 0) > 0 || collapsedEmailLogin) && /* @__PURE__ */ createElement(Stack, {
    direction: "vertical"
  }, identityProviders?.map((it, i) => /* @__PURE__ */ createElement(IDPInitButton, {
    key: i,
    provider: it,
    onError: setError
  })), collapsedEmailLogin && /* @__PURE__ */ createElement(Button, {
    onClick: () => setCollapsedEmailLogin(false)
  }, "Login with email")));
};
export { LoginEntrypoint };
//# sourceMappingURL=LoginEntrypoint.js.map
