import { jsx, jsxs } from "react/jsx-runtime";
import { getTenantErrorMessage } from "@contember/client";
import { useSetSessionToken } from "@contember/react-client";
import { Stack, ErrorList, FieldContainer, EmailInput, PasswordInput, TextInput, Button } from "@contember/ui";
import { useState, useCallback } from "react";
import { useSignIn } from "../../mutations/identity/signIn.js";
import { Link } from "../../../routing/Link.js";
import { useForm } from "../../lib/useForm.js";
const initialValues = {
  email: "",
  password: "",
  otpToken: ""
};
const Login = ({ onLogin, resetLink }) => {
  const [errors, setErrors] = useState([]);
  const [otpRequired, setOtpRequired] = useState(false);
  const login = useSignIn();
  const setSessionToken = useSetSessionToken();
  const { onSubmit, isSubmitting, register } = useForm(initialValues, 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: getTenantErrorMessage(error.code) }]);
      }
    } else {
      setSessionToken(response.result.token);
      onLogin?.();
    }
  }, [login, onLogin, setSessionToken]));
  return /* @__PURE__ */ jsx("form", { onSubmit, children: /* @__PURE__ */ jsxs(Stack, { gap: "large", children: [
    /* @__PURE__ */ jsx(ErrorList, { errors }),
    /* @__PURE__ */ jsx(FieldContainer, { label: "Email", children: /* @__PURE__ */ jsx(
      EmailInput,
      {
        ...register("email"),
        autoComplete: "username",
        autoFocus: !otpRequired,
        disabled: otpRequired
      }
    ) }),
    /* @__PURE__ */ jsx(FieldContainer, { label: "Password", children: /* @__PURE__ */ jsx(
      PasswordInput,
      {
        ...register("password"),
        autoComplete: "current-password",
        disabled: otpRequired
      }
    ) }),
    otpRequired && /* @__PURE__ */ jsx(FieldContainer, { label: "Two-factor code", children: /* @__PURE__ */ jsx(
      TextInput,
      {
        autoFocus: true,
        autoComplete: "one-time-code",
        ...register("otpToken")
      }
    ) }),
    /* @__PURE__ */ jsxs(Stack, { horizontal: true, align: "center", justify: "space-between", children: [
      resetLink && /* @__PURE__ */ jsx(Link, { to: resetLink, children: "Forgot your password?" }),
      /* @__PURE__ */ jsx(Button, { type: "submit", distinction: "primary", display: "block", disabled: isSubmitting, children: "Submit" })
    ] })
  ] }) });
};
export {
  Login
};
//# sourceMappingURL=Login.js.map
