"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const client = require("@contember/client");
const reactClient = require("@contember/react-client");
const ui = require("@contember/ui");
const react = require("react");
const signIn = require("../../mutations/identity/signIn.cjs");
const Link = require("../../../routing/Link.cjs");
const useForm = require("../../lib/useForm.cjs");
const initialValues = {
  email: "",
  password: "",
  otpToken: ""
};
const Login = ({ onLogin, resetLink }) => {
  const [errors, setErrors] = react.useState([]);
  const [otpRequired, setOtpRequired] = react.useState(false);
  const login = signIn.useSignIn();
  const setSessionToken = reactClient.useSetSessionToken();
  const { onSubmit, isSubmitting, register } = useForm.useForm(initialValues, react.useCallback(async (values) => {
    const response = await login({
      email: values.email,
      password: values.password,
      otpToken: values.otpToken || void 0,
      expiration: 14 * 24 * 3600
    });
    setErrors([]);
    if (!response.ok) {
      const error = response.error;
      if (response.error.code === "OTP_REQUIRED") {
        setOtpRequired(true);
      } else {
        setErrors([{ message: client.getTenantErrorMessage(error.code) }]);
      }
    } else {
      setSessionToken(response.result.token);
      onLogin?.();
    }
  }, [login, onLogin, setSessionToken]));
  return /* @__PURE__ */ jsxRuntime.jsx("form", { onSubmit, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { gap: "large", children: [
    /* @__PURE__ */ jsxRuntime.jsx(ui.ErrorList, { errors }),
    /* @__PURE__ */ jsxRuntime.jsx(ui.FieldContainer, { label: "Email", children: /* @__PURE__ */ jsxRuntime.jsx(
      ui.EmailInput,
      {
        ...register("email"),
        autoComplete: "username",
        autoFocus: !otpRequired,
        disabled: otpRequired
      }
    ) }),
    /* @__PURE__ */ jsxRuntime.jsx(ui.FieldContainer, { label: "Password", children: /* @__PURE__ */ jsxRuntime.jsx(
      ui.PasswordInput,
      {
        ...register("password"),
        autoComplete: "current-password",
        disabled: otpRequired
      }
    ) }),
    otpRequired && /* @__PURE__ */ jsxRuntime.jsx(ui.FieldContainer, { label: "Two-factor code", children: /* @__PURE__ */ jsxRuntime.jsx(
      ui.TextInput,
      {
        autoFocus: true,
        autoComplete: "one-time-code",
        ...register("otpToken")
      }
    ) }),
    /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { horizontal: true, align: "center", justify: "space-between", children: [
      resetLink && /* @__PURE__ */ jsxRuntime.jsx(Link.Link, { to: resetLink, children: "Forgot your password?" }),
      /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { type: "submit", distinction: "primary", display: "block", disabled: isSubmitting, children: "Submit" })
    ] })
  ] }) });
};
exports.Login = Login;
//# sourceMappingURL=Login.cjs.map
