import { jsx, jsxs } from "react/jsx-runtime";
import { getTenantErrorMessage } from "@contember/client";
import { useSetSessionToken } from "@contember/react-client";
import { Stack, ErrorList, FieldContainer, TextInput, Button } from "@contember/ui";
import { useState, useCallback } from "react";
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__ */ jsx("form", { onSubmit, children: /* @__PURE__ */ jsxs(Stack, { direction: "vertical", gap: "large", children: [
    /* @__PURE__ */ jsx(ErrorList, { errors }),
    /* @__PURE__ */ jsx(FieldContainer, { label: "Email", children: /* @__PURE__ */ jsx(
      TextInput,
      {
        ...register("email"),
        autoComplete: "username",
        type: "email",
        autoFocus: !otpRequired,
        disabled: otpRequired
      }
    ) }),
    /* @__PURE__ */ jsx(FieldContainer, { label: "Password", children: /* @__PURE__ */ jsx(
      TextInput,
      {
        ...register("password"),
        type: "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, { direction: "horizontal", align: "center", justify: "space-between", children: [
      /* @__PURE__ */ jsx(Button, { type: "submit", distinction: "primary", disabled: isSubmitting, children: "Submit" }),
      resetLink && /* @__PURE__ */ jsx(Link, { to: resetLink, children: "Forgot your password?" })
    ] })
  ] }) });
};
export {
  Login
};
//# sourceMappingURL=Login.js.map
