import jsonpointer from "jsonpointer";
import { useCallback, useEffect, useRef } from "@saasquatch/universal-hooks";
import { navigation, useRegisterWithEmailAndPasswordMutation, } from "@saasquatch/component-boilerplate";
import { AsYouType } from "libphonenumber-js";
import { useRegistrationFormState } from "../sqm-portal-registration-form/useRegistrationFormState";
export function usePortalRegister(props) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _j;
  const formRef = useRef(null);
  const { registrationFormState, setRegistrationFormState } = useRegistrationFormState({});
  const [request, { loading, errors, data }] = useRegisterWithEmailAndPasswordMutation();
  useEffect(() => {
    if (!formRef.current)
      return;
    const form = formRef.current;
    form.addEventListener("sl-input", inputFunction);
    return () => {
      form.removeEventListener("sl-input", inputFunction);
    };
  }, [formRef.current]);
  const submit = async (event) => {
    var _a;
    let formControls = event.target.getFormControls();
    let formData = {};
    let validationErrors = {};
    formControls === null || formControls === void 0 ? void 0 : formControls.forEach((control) => {
      if (!control.name)
        return;
      const key = control.name;
      const value = control.value;
      jsonpointer.set(formData, key, value);
      // required validation
      if (control.required && !value) {
        jsonpointer.set(validationErrors, key, props.requiredFieldErrorMessage);
      }
      // custom validation
      if (typeof control.validationError === "function") {
        const validate = control.validationError;
        const validationError = validate({ control, key, value });
        if (validationError)
          jsonpointer.set(validationErrors, key, validationError);
      }
    });
    if ((props.confirmPassword || formData.confirmPassword) &&
      formData.password !== formData.confirmPassword) {
      validationErrors = {
        ...validationErrors,
        confirmPassword: props.passwordMismatchErrorMessage,
      };
    }
    if (Object.keys(validationErrors).length) {
      setRegistrationFormState({ loading: false, error: "", validationErrors });
      // early return for validation errors
      return;
    }
    setRegistrationFormState({
      loading: true,
      error: "",
      validationErrors: {},
    });
    const { email, password } = formData;
    delete formData.email;
    delete formData.password;
    delete formData.confirmPassword;
    formData = { ...formData };
    const redirectPath = props.redirectPath;
    const variables = {
      email,
      password,
      formData,
      redirectPath,
    };
    try {
      const result = await request(variables);
      if (result instanceof Error) {
        throw result;
      }
      setRegistrationFormState({
        loading: false,
        error: "",
        validationErrors: {},
      });
      if ((_a = result.registerManagedIdentityWithEmailAndPassword) === null || _a === void 0 ? void 0 : _a.token) {
        navigation.push(props.nextPage);
      }
    }
    catch (error) {
      setRegistrationFormState({
        loading: false,
        error: props.networkErrorMessage,
        validationErrors: {},
      });
    }
  };
  const inputFunction = useCallback((e) => {
    var _a, _b;
    const name = (_b = (_a = e.target) === null || _a === void 0 ? void 0 : _a.type) === null || _b === void 0 ? void 0 : _b.toLowerCase();
    if (name !== "tel")
      return;
    const asYouType = new AsYouType("US");
    e.target.value = asYouType.input(e.target.value);
  }, []);
  let errorMessage = "";
  if ((_a = errors === null || errors === void 0 ? void 0 : errors.response) === null || _a === void 0 ? void 0 : _a["error"]) {
    errorMessage = props.networkErrorMessage;
  }
  else if ((errors === null || errors === void 0 ? void 0 : errors.message) && !((_b = errors === null || errors === void 0 ? void 0 : errors.response) === null || _b === void 0 ? void 0 : _b.errors.length)) {
    errorMessage = props.networkErrorMessage;
  }
  else {
    errorMessage =
      ((_f = (_e = (_d = (_c = errors === null || errors === void 0 ? void 0 : errors.response) === null || _c === void 0 ? void 0 : _c.errors) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.extensions) === null || _f === void 0 ? void 0 : _f.message) || ((_j = (_h = (_g = errors === null || errors === void 0 ? void 0 : errors.response) === null || _g === void 0 ? void 0 : _g.errors) === null || _h === void 0 ? void 0 : _h[0]) === null || _j === void 0 ? void 0 : _j.message) || (registrationFormState === null || registrationFormState === void 0 ? void 0 : registrationFormState.error);
  }
  return {
    states: {
      loading,
      error: errorMessage,
      registrationFormState,
      confirmPassword: props.confirmPassword,
      hideInputs: props.hideInputs,
      loginPath: props.loginPath,
      disablePasswordValidation: props.disablePasswordValidation,
    },
    callbacks: {
      submit,
      inputFunction,
    },
    refs: {
      formRef,
    },
  };
}
