"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

require("core-js/modules/web.dom-collections.iterator.js");

require("core-js/modules/es.promise.js");

require("core-js/modules/es.json.stringify.js");

var _react = _interopRequireWildcard(require("react"));

var _icons = require("@ant-design/icons");

var _antd = require("antd");

var _formik = require("formik");

var Yup = _interopRequireWildcard(require("yup"));

require("antd/dist/antd.css");

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactRouterDom = require("react-router-dom");

var _constant = require("../constant");

var _SignupFormModule = _interopRequireDefault(require("./SignupForm.module.scss"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

const SignupForm = _ref => {
  var _isAuthenticate$messa;

  let {
    background,
    textColor,
    label,
    storeToken,
    realm,
    clientId,
    authhandlerUrl,
    backendUrl
  } = _ref;
  const INITIAL_DATA_API = "".concat(backendUrl, "/staff/initial-data");

  const initialDataHeaders = _objectSpread(_objectSpread({}, _constant.signinApiHeaders), {}, {
    organizationName: "hcinbox"
  });

  const signUpLabel = "Sign Up";
  const navigate = (0, _reactRouterDom.useNavigate)();
  const {
    invitationId
  } = (0, _reactRouterDom.useParams)();
  const SIGNUP_API = !invitationId ? "".concat(authhandlerUrl, "/staff") : "".concat(backendUrl, "/staff/signup-with-invitation");
  const {
    values,
    touched,
    errors,
    handleChange,
    handleBlur,
    handleSubmit
  } = (0, _formik.useFormik)({
    initialValues: {
      firstName: "",
      lastName: "",
      email: "",
      password: ""
    },
    validationSchema: Yup.object().shape({
      firstName: Yup.string().required("First name required"),
      email: Yup.string().email("Invalid email address format").required("Email required"),
      password: Yup.string().matches(/^(?=.*[A-Za-z])(?=.*[@$!%*#?&])[A-Za-z0-9@$!%*#?&]{6,}$/, "Password should be atleast 6 characters long and should contain a special symbol!").required("Password required")
    }),
    onSubmit: async values => {
      submitSignupForm(values);
    }
  });
  const [isAuthenticate, setAuthenticationStatus] = (0, _react.useState)({
    status: false,
    message: ""
  });
  const [loading, setLoading] = (0, _react.useState)(false);

  const submitSignupForm = async formValues => {
    const {
      firstName,
      lastName,
      email,
      password
    } = formValues;
    let res = null;
    let userDetails = null;
    let body = null;
    let tokenSet = null;

    try {
      setLoading(true);

      if (invitationId) {
        body = _objectSpread(_objectSpread({}, formValues), {}, {
          invitationId
        });
      } else {
        body = _objectSpread({}, formValues);
      }

      res = await fetch(SIGNUP_API, {
        method: "POST",
        headers: _constant.signinApiHeaders,
        body: JSON.stringify(body)
      });

      if (!res.ok) {
        throw new Error(res);
      }

      tokenSet = await res.json();

      if (tokenSet.error) {
        throw new Error(tokenSet);
      }

      storeToken(tokenSet);
      initialDataHeaders.Authorization = "Bearer ".concat(tokenSet.access_token);
      userDetails = await fetch(INITIAL_DATA_API, {
        headers: initialDataHeaders
      });

      if (!userDetails.ok) {
        throw new Error(userDetails);
      }

      userDetails = await userDetails.json();

      if (!userDetails.success) {
        throw new Error("Server Error!");
      }

      localStorage.setItem('userDetails', JSON.stringify(userDetails.data));
      setAuthenticationStatus(_objectSpread(_objectSpread({}, isAuthenticate), {}, {
        status: true,
        message: ""
      }));
      setLoading(false);
      navigate("/chat");
    } catch (error) {
      sessionStorage.removeItem("access_token");
      sessionStorage.removeItem("refresh_token");
      let msg;
      setLoading(false);

      if (userDetails !== null) {
        msg = await userDetails.json();
        setAuthenticationStatus(_objectSpread(_objectSpread({}, isAuthenticate), {}, {
          status: false,
          message: msg.error
        }));
      } else {
        if (tokenSet === null) {
          msg = await res.json();
        }

        setAuthenticationStatus(_objectSpread(_objectSpread({}, isAuthenticate), {}, {
          status: false,
          message: !msg ? tokenSet.error : msg.message
        }));
      }
    }
  };

  const handleValidationStatus = key => {
    return !touched[key] && !errors[key] ? "" : touched[key] && !errors[key] ? "success" : touched[key] && errors[key] ? "error" : "";
  };

  return /*#__PURE__*/_react.default.createElement("div", {
    className: _SignupFormModule.default.SignupForm
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: _SignupFormModule.default.SignupForm__signUpContainer
  }, /*#__PURE__*/_react.default.createElement("h3", null, "Great to have you here"), /*#__PURE__*/_react.default.createElement("form", {
    onSubmit: handleSubmit
  }, /*#__PURE__*/_react.default.createElement(_antd.Row, {
    className: _SignupFormModule.default.SignupForm__signUpContainer__name,
    gutter: [16]
  }, /*#__PURE__*/_react.default.createElement(_antd.Col, {
    span: 12
  }, /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SignupFormModule.default.SignupForm__signUpContainer__formItem,
    label: "First Name",
    name: "firstName",
    validateStatus: handleValidationStatus("firstName"),
    hasFeedback: true
  }, /*#__PURE__*/_react.default.createElement(_antd.Input, {
    id: "firstName",
    name: "firstName",
    type: "text",
    onChange: handleChange,
    onBlur: handleBlur,
    value: values.firstName,
    placeholder: "input first name"
  }), touched.firstName && errors.firstName ? /*#__PURE__*/_react.default.createElement("div", {
    role: "alert",
    className: _SignupFormModule.default.SignupForm__signUpContainer__formItem__error
  }, errors.firstName) : null)), /*#__PURE__*/_react.default.createElement(_antd.Col, {
    span: 12
  }, /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SignupFormModule.default.SignupForm__signUpContainer__formItem,
    label: "Last Name",
    name: "lastName",
    hasFeedback: true
  }, /*#__PURE__*/_react.default.createElement(_antd.Input, {
    id: "lastName",
    name: "lastName",
    type: "text",
    onChange: handleChange,
    onBlur: handleBlur,
    value: values.lastName,
    placeholder: "input last name"
  })))), /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SignupFormModule.default.SignupForm__signUpContainer__formItem,
    label: "Email",
    name: "email",
    validateStatus: handleValidationStatus("email"),
    hasFeedback: true
  }, /*#__PURE__*/_react.default.createElement(_antd.Input, {
    id: "email",
    name: "email",
    type: "text",
    onChange: handleChange,
    onBlur: handleBlur,
    value: values.email,
    placeholder: "example@gmail.com"
  }), touched.email && errors.email ? /*#__PURE__*/_react.default.createElement("div", {
    role: "alert",
    className: _SignupFormModule.default.SignupForm__signUpContainer__formItem__error
  }, errors.email) : null), /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SignupFormModule.default.SignupForm__signUpContainer__formItem,
    label: "Password",
    name: "password",
    validateStatus: handleValidationStatus("password"),
    hasFeedback: true
  }, /*#__PURE__*/_react.default.createElement(_antd.Input.Password, {
    id: "password",
    name: "password",
    type: "text",
    onChange: handleChange,
    onBlur: handleBlur,
    value: values.password,
    placeholder: "Password"
  }), touched.password && errors.password ? /*#__PURE__*/_react.default.createElement("div", {
    role: "alert",
    className: _SignupFormModule.default.SignupForm__signUpContainer__formItem__error
  }, errors.password) : null), /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SignupFormModule.default.SignupForm__signUpContainer__formItem
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: _SignupFormModule.default.SignupForm__signUpContainer__formItem__signUpBtnContainer
  }, /*#__PURE__*/_react.default.createElement(_antd.Button, {
    "data-testid": "sign-up-btn",
    style: {
      background: background,
      color: textColor
    },
    loading: loading,
    htmlType: "submit",
    icon: /*#__PURE__*/_react.default.createElement(_icons.LoginOutlined, null)
  }, invitationId ? label : signUpLabel))), /*#__PURE__*/_react.default.createElement("div", {
    className: _SignupFormModule.default.SignupForm__signUpContainer__helpMsg
  }, "Already have an account? ", /*#__PURE__*/_react.default.createElement("a", {
    onClick: () => navigate("/login")
  }, "Signin here")), (_isAuthenticate$messa = isAuthenticate.message) !== null && _isAuthenticate$messa !== void 0 && _isAuthenticate$messa.length ? /*#__PURE__*/_react.default.createElement("div", {
    className: _SignupFormModule.default.alert
  }, /*#__PURE__*/_react.default.createElement(_antd.Alert, {
    message: "Error",
    description: isAuthenticate.message,
    className: _SignupFormModule.default.SignupForm__signUpContainer__errorMsg,
    type: "error",
    showIcon: true
  })) : null), /*#__PURE__*/_react.default.createElement("footer", {
    className: _SignupFormModule.default.SignupForm__footer,
    "data-testid": "footer"
  }, "Need help? ", /*#__PURE__*/_react.default.createElement("span", null, "Feel free to"), "\xA0", /*#__PURE__*/_react.default.createElement("a", {
    href: "#"
  }, "Contact Us!"))));
};

SignupForm.propTypes = {
  background: _propTypes.default.string,
  textColor: _propTypes.default.string,
  label: _propTypes.default.string,
  size: _propTypes.default.string
};
SignupForm.defaultProps = {
  background: "rgba(9, 109, 217, 1)",
  textColor: "white",
  label: "Accept Invite",
  size: "medium"
};
var _default = SignupForm;
exports.default = _default;