import { useState, useCallback, createElement } from "react";
import { getTenantErrorMessage } from "@contember/client";
import { useSetSessionToken } from "@contember/react-client";
import { Stack, ErrorList, FieldContainer, TextInput, Button } from "@contember/ui";
import { useSignIn } from "../../mutations/identity/signIn.js";
import { Link } from "../../../routing/binding/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__ */ createElement("form", {
    onSubmit
  }, /* @__PURE__ */ createElement(Stack, {
    direction: "vertical",
    gap: "large"
  }, /* @__PURE__ */ createElement(ErrorList, {
    errors
  }), /* @__PURE__ */ createElement(FieldContainer, {
    label: "Email"
  }, /* @__PURE__ */ createElement(TextInput, {
    ...register("email"),
    autoComplete: "username",
    type: "email",
    autoFocus: !otpRequired,
    disabled: otpRequired
  })), /* @__PURE__ */ createElement(FieldContainer, {
    label: "Password"
  }, /* @__PURE__ */ createElement(TextInput, {
    ...register("password"),
    type: "password",
    autoComplete: "current-password",
    disabled: otpRequired
  })), otpRequired && /* @__PURE__ */ createElement(FieldContainer, {
    label: "Two-factor code"
  }, /* @__PURE__ */ createElement(TextInput, {
    autoFocus: true,
    autoComplete: "one-time-code",
    ...register("otpToken")
  })), /* @__PURE__ */ createElement(Stack, {
    direction: "horizontal",
    align: "center",
    justify: "space-between"
  }, /* @__PURE__ */ createElement(Button, {
    type: "submit",
    distinction: "primary",
    disabled: isSubmitting
  }, "Submit"), resetLink && /* @__PURE__ */ createElement(Link, {
    to: resetLink
  }, "Forgot your password?"))));
};
export { Login };
//# sourceMappingURL=Login.js.map
