import { ContemberClient } from "@contember/react-client";
import { StyleProvider, ToasterProvider, Toaster, Button, Icon, ErrorList, Stack } from "@contember/ui";
import { useState, useEffect, useMemo, useCallback } from "react";
import { MiscPageLayout } from "../MiscPageLayout.js";
import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
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";
var _jsxFileName = "/__w/interface/interface/packages/admin/src/components/Login/LoginEntrypoint.tsx";
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__ */ jsxDEV(ContemberClient, {
    apiBaseUrl: props.apiBaseUrl,
    sessionToken: props.sessionToken,
    loginToken: props.loginToken,
    children: /* @__PURE__ */ jsxDEV(StyleProvider, {
      children: /* @__PURE__ */ jsxDEV(ToasterProvider, {
        children: [/* @__PURE__ */ jsxDEV(RoutingContext.Provider, {
          value: routing,
          children: /* @__PURE__ */ jsxDEV(RequestProvider, {
            children: /* @__PURE__ */ jsxDEV(Pages, {
              children: [/* @__PURE__ */ jsxDEV(Page, {
                name: indexPageName,
                children: /* @__PURE__ */ jsxDEV(IdentityProvider, {
                  allowUnauthenticated: true,
                  children: /* @__PURE__ */ jsxDEV(LoginEntrypointIndex, {
                    projects: props.projects,
                    formatProjectUrl: props.formatProjectUrl,
                    identityProviders: props.identityProviders,
                    heading: props.heading,
                    projectsPageActions: props.projectsPageActions,
                    collapsedEmailLogin: props.collapsedEmailLogin
                  }, void 0, false, {
                    fileName: _jsxFileName,
                    lineNumber: 59,
                    columnNumber: 11
                  }, void 0)
                }, void 0, false, {
                  fileName: _jsxFileName,
                  lineNumber: 58,
                  columnNumber: 10
                }, void 0)
              }, void 0, false, {
                fileName: _jsxFileName,
                lineNumber: 57,
                columnNumber: 9
              }, void 0), /* @__PURE__ */ jsxDEV(Page, {
                name: resetRequestPageName,
                children: /* @__PURE__ */ jsxDEV(MiscPageLayout, {
                  heading: "Password reset",
                  actions: /* @__PURE__ */ jsxDEV(Fragment, {
                    children: /* @__PURE__ */ jsxDEV(Link, {
                      to: indexPageName,
                      children: "\u2190 Back to login"
                    }, void 0, false, {
                      fileName: _jsxFileName,
                      lineNumber: 71,
                      columnNumber: 11
                    }, void 0)
                  }, void 0, false),
                  children: /* @__PURE__ */ jsxDEV(CreateResetPasswordRequestForm, {
                    redirectOnSuccess: redirectOnSuccessPageName
                  }, void 0, false, {
                    fileName: _jsxFileName,
                    lineNumber: 73,
                    columnNumber: 11
                  }, void 0)
                }, void 0, false, {
                  fileName: _jsxFileName,
                  lineNumber: 70,
                  columnNumber: 10
                }, void 0)
              }, void 0, false, {
                fileName: _jsxFileName,
                lineNumber: 69,
                columnNumber: 9
              }, void 0), /* @__PURE__ */ jsxDEV(Page, {
                name: redirectOnSuccessPageName,
                children: /* @__PURE__ */ jsxDEV(MiscPageLayout, {
                  heading: "Password reset",
                  actions: /* @__PURE__ */ jsxDEV(Fragment, {
                    children: /* @__PURE__ */ jsxDEV(Link, {
                      to: indexPageName,
                      children: "\u2190 Back to login"
                    }, void 0, false, {
                      fileName: _jsxFileName,
                      lineNumber: 78,
                      columnNumber: 11
                    }, void 0)
                  }, void 0, false),
                  children: [/* @__PURE__ */ jsxDEV("p", {
                    children: "Password reset request has been successfully created. Please check your inbox for the instructions."
                  }, void 0, false, {
                    fileName: _jsxFileName,
                    lineNumber: 80,
                    columnNumber: 11
                  }, void 0), /* @__PURE__ */ jsxDEV("p", {
                    children: "Please follow the link in e-mail or copy the reset token here:"
                  }, void 0, false, {
                    fileName: _jsxFileName,
                    lineNumber: 83,
                    columnNumber: 11
                  }, void 0), /* @__PURE__ */ jsxDEV(FillResetPasswordTokenForm, {
                    resetLink: `${passwordResetPageName}(token: $token)`
                  }, void 0, false, {
                    fileName: _jsxFileName,
                    lineNumber: 86,
                    columnNumber: 11
                  }, void 0)]
                }, void 0, true, {
                  fileName: _jsxFileName,
                  lineNumber: 77,
                  columnNumber: 10
                }, void 0)
              }, void 0, false, {
                fileName: _jsxFileName,
                lineNumber: 76,
                columnNumber: 9
              }, void 0), /* @__PURE__ */ jsxDEV(Page, {
                name: passwordResetPageName,
                children: ({
                  token
                }) => /* @__PURE__ */ jsxDEV(MiscPageLayout, {
                  heading: "Set a new password",
                  actions: /* @__PURE__ */ jsxDEV(Fragment, {
                    children: /* @__PURE__ */ jsxDEV(Link, {
                      to: indexPageName,
                      children: "\u2190 Back to login"
                    }, void 0, false, {
                      fileName: _jsxFileName,
                      lineNumber: 92,
                      columnNumber: 12
                    }, void 0)
                  }, void 0, false),
                  children: /* @__PURE__ */ jsxDEV(ResetPasswordForm, {
                    token,
                    redirectOnSuccess: indexPageName
                  }, void 0, false, {
                    fileName: _jsxFileName,
                    lineNumber: 94,
                    columnNumber: 12
                  }, void 0)
                }, void 0, false, {
                  fileName: _jsxFileName,
                  lineNumber: 91,
                  columnNumber: 11
                }, void 0)
              }, void 0, false, {
                fileName: _jsxFileName,
                lineNumber: 89,
                columnNumber: 9
              }, void 0)]
            }, void 0, true, {
              fileName: _jsxFileName,
              lineNumber: 56,
              columnNumber: 8
            }, void 0)
          }, void 0, false, {
            fileName: _jsxFileName,
            lineNumber: 55,
            columnNumber: 7
          }, void 0)
        }, void 0, false, {
          fileName: _jsxFileName,
          lineNumber: 54,
          columnNumber: 6
        }, void 0), /* @__PURE__ */ jsxDEV(Toaster, {}, void 0, false, {
          fileName: _jsxFileName,
          lineNumber: 101,
          columnNumber: 6
        }, void 0)]
      }, void 0, true, {
        fileName: _jsxFileName,
        lineNumber: 53,
        columnNumber: 5
      }, void 0)
    }, void 0, false, {
      fileName: _jsxFileName,
      lineNumber: 52,
      columnNumber: 4
    }, void 0)
  }, void 0, false, {
    fileName: _jsxFileName,
    lineNumber: 47,
    columnNumber: 3
  }, void 0);
};
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__ */ jsxDEV(MiscPageLayout, {
      heading: props.heading ?? "Contember Admin",
      children: /* @__PURE__ */ jsxDEV(LoginContainer, {
        identityProviders: props.identityProviders,
        collapsedEmailLogin: props.collapsedEmailLogin
      }, void 0, false, {
        fileName: _jsxFileName,
        lineNumber: 129,
        columnNumber: 5
      }, void 0)
    }, void 0, false, {
      fileName: _jsxFileName,
      lineNumber: 128,
      columnNumber: 4
    }, void 0);
  } else if (projects === void 0) {
    return /* @__PURE__ */ jsxDEV(MiscPageLayout, {
      heading: "Projects",
      actions: /* @__PURE__ */ jsxDEV(Fragment, {
        children: [props.projectsPageActions, /* @__PURE__ */ jsxDEV(Button, {
          onClick: () => logout(),
          size: "small",
          distinction: "seamless",
          children: /* @__PURE__ */ jsxDEV(Icon, {
            blueprintIcon: "log-out"
          }, void 0, false, {
            fileName: _jsxFileName,
            lineNumber: 139,
            columnNumber: 79
          }, void 0)
        }, void 0, false, {
          fileName: _jsxFileName,
          lineNumber: 139,
          columnNumber: 6
        }, void 0)]
      }, void 0, true),
      children: "Loading projects..."
    }, void 0, false, {
      fileName: _jsxFileName,
      lineNumber: 135,
      columnNumber: 4
    }, void 0);
  } else if (projects.length === 1) {
    window.location.href = props.formatProjectUrl(projects[0]);
    return null;
  } else {
    return /* @__PURE__ */ jsxDEV(MiscPageLayout, {
      heading: "Projects",
      actions: props.projectsPageActions,
      footerActions: /* @__PURE__ */ jsxDEV(Button, {
        onClick: () => logout(),
        distinction: "seamless",
        flow: "block",
        children: ["Sign out ", /* @__PURE__ */ jsxDEV(Icon, {
          blueprintIcon: "log-out"
        }, void 0, false, {
          fileName: _jsxFileName,
          lineNumber: 155,
          columnNumber: 98
        }, void 0)]
      }, void 0, true, {
        fileName: _jsxFileName,
        lineNumber: 155,
        columnNumber: 20
      }, void 0),
      children: /* @__PURE__ */ jsxDEV(ProjectListButtons, {
        projects,
        formatProjectUrl: props.formatProjectUrl
      }, void 0, false, {
        fileName: _jsxFileName,
        lineNumber: 157,
        columnNumber: 5
      }, void 0)
    }, void 0, false, {
      fileName: _jsxFileName,
      lineNumber: 152,
      columnNumber: 4
    }, void 0);
  }
};
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__ */ jsxDEV(IDPResponseHandler, {
      onLogin: onLoginHandler
    }, void 0, false, {
      fileName: _jsxFileName,
      lineNumber: 188,
      columnNumber: 10
    }, void 0);
  }
  return /* @__PURE__ */ jsxDEV(Fragment, {
    children: [/* @__PURE__ */ jsxDEV(ErrorList, {
      errors: error ? [{
        message: error
      }] : []
    }, void 0, false, {
      fileName: _jsxFileName,
      lineNumber: 192,
      columnNumber: 3
    }, void 0), !collapsedEmailLogin && /* @__PURE__ */ jsxDEV(Login, {
      resetLink: resetRequestPageName,
      onLogin: onLoginHandler
    }, void 0, false, {
      fileName: _jsxFileName,
      lineNumber: 193,
      columnNumber: 28
    }, void 0), ((identityProviders?.length ?? 0) > 0 || collapsedEmailLogin) && /* @__PURE__ */ jsxDEV(Stack, {
      direction: "vertical",
      children: [identityProviders?.map((it, i) => /* @__PURE__ */ jsxDEV(IDPInitButton, {
        provider: it,
        onError: setError
      }, i, false, {
        fileName: _jsxFileName,
        lineNumber: 196,
        columnNumber: 40
      }, void 0)), collapsedEmailLogin && /* @__PURE__ */ jsxDEV(Button, {
        onClick: () => setCollapsedEmailLogin(false),
        children: "Login with email"
      }, void 0, false, {
        fileName: _jsxFileName,
        lineNumber: 197,
        columnNumber: 29
      }, void 0)]
    }, void 0, true, {
      fileName: _jsxFileName,
      lineNumber: 195,
      columnNumber: 4
    }, void 0)]
  }, void 0, true);
};
export {
  LoginEntrypoint
};
//# sourceMappingURL=LoginEntrypoint.js.map
