"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");

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

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

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

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

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

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

var _formik = require("formik");

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

var _axios = _interopRequireDefault(require("axios"));

var _antd = require("antd");

var _freeRegularSvgIcons = require("@fortawesome/free-regular-svg-icons");

var _reactFontawesome = require("@fortawesome/react-fontawesome");

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

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

var _SigninFormModule = _interopRequireDefault(require("./SigninForm.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 SigninForm = _ref => {
  let {
    background,
    textColor,
    label,
    storeToken,
    authhandlerUrl,
    backendUrl
  } = _ref;
  const [isAuthenticate, setAuthenticationStatus] = (0, _react.useState)(undefined);
  const [loading, setLoading] = (0, _react.useState)(false);
  const [isPaswordResetEmailSend, setPaswordResetEmailSendStatus] = (0, _react.useState)(false);
  const [message, setMessage] = (0, _react.useState)({
    success: null,
    error: null
  });
  const navigate = (0, _reactRouterDom.useNavigate)();
  const location = (0, _reactRouterDom.useLocation)();
  const {
    staffId,
    resetPasswordId
  } = (0, _reactRouterDom.useParams)();
  const isResetPasswordPage = staffId && resetPasswordId;
  const isForgotPasswordPage = location.pathname === "/forgot-password";
  const INITIAL_DATA_API = "".concat(backendUrl, "/staff/initial-data");
  const SIGNIN_API = "".concat(authhandlerUrl, "/auth");

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

  (0, _react.useEffect)(() => {
    handleForgotScreenToogle(false);
  }, [location.pathname]);
  const {
    values,
    touched,
    errors,
    handleChange,
    handleBlur,
    handleSubmit,
    resetForm
  } = (0, _formik.useFormik)({
    initialValues: {
      email: "",
      password: "",
      passwordConfirmation: ""
    },
    validationSchema: Yup.object().shape({
      email: Yup.string().email("Invalid email address format").required("Email required"),
      password: !isForgotPasswordPage ? 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") : null,
      passwordConfirmation: isResetPasswordPage ? Yup.string().oneOf([Yup.ref('password'), null], 'Passwords must match').required("Confirm password") : null
    }),
    onSubmit: async values => {
      if (isForgotPasswordPage && !isResetPasswordPage) {
        submitEmailConfirmation(values);
      } else if (isResetPasswordPage && !isForgotPasswordPage) {
        submitPasswordReset(values);
      } else {
        submitSignInForm(values);
      }
    }
  });

  const submitSignInForm = async _ref2 => {
    let {
      email,
      password
    } = _ref2;

    try {
      setLoading(true);
      const token = await fetch(SIGNIN_API, {
        method: "POST",
        headers: _constant.signinApiHeaders,
        body: JSON.stringify({
          username: email,
          password
        })
      });
      const tokenSet = await token.json();
      storeToken(tokenSet);
      initialDataHeaders.Authorization = "Bearer ".concat(tokenSet.access_token);
      let 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(true);
      setLoading(false);
      navigate("/chat");
    } catch (error) {
      setLoading(false);
      setAuthenticationStatus(false);
      setMessage(_objectSpread(_objectSpread({}, message), {}, {
        error: {
          title: "Error",
          description: "Couldn’t find a HCInbox account associated with this credentials. Please try again.",
          type: "error",
          showIcon: true
        }
      }));
      console.log(error);
    }
  };

  const submitEmailConfirmation = values => {
    setLoading(true);
    setPaswordResetEmailSendStatus(true);

    _axios.default.post("".concat(backendUrl, "/staff/reset-password"), {
      email: values.email
    }).then(resp => {
      if (Boolean(resp.data.success)) {
        setMessage(_objectSpread(_objectSpread({}, message), {}, {
          success: {
            title: "Success",
            description: "An email for reset password is sent to your email address. Please check your email for password reset instructions.",
            type: "success",
            showIcon: true
          }
        }));
        handleForgotScreenToogle(true);
      } else {
        const {
          error
        } = resp.data;
        setMessage(_objectSpread(_objectSpread({}, message), {}, {
          success: {
            title: "Error",
            description: error.replace(error[0], error[0].toUpperCase()),
            type: "error",
            showIcon: true
          }
        }));
      }

      setLoading(false);
    }).catch(error => {
      setMessage(_objectSpread(_objectSpread({}, message), {}, {
        success: {
          title: "Error",
          description: error.message,
          type: "error",
          showIcon: true
        }
      }));
      setLoading(false);
    });
  };

  const submitPasswordReset = _ref3 => {
    let {
      email,
      password
    } = _ref3;
    setLoading(true);
    const passwordResetSuccessMsg = "Password is successfully updated";
    const passwordResetFailureMsg = "Failed to update the password";

    _axios.default.put("".concat(backendUrl, "/staff/update/password"), {
      email,
      password,
      resetPasswordId
    }).then(resp => {
      setLoading(false);

      if (Boolean(resp.data.success)) {
        _antd.notification["success"]({
          message: 'Success',
          description: passwordResetSuccessMsg,
          duration: 5.5
        });

        navigate("/");
        handleForgotScreenToogle(false);
      } else {
        _antd.notification["error"]({
          message: 'Failure',
          description: passwordResetFailureMsg,
          duration: 5.5
        });
      }
    }).catch(error => {
      setLoading(false);

      _antd.notification["error"]({
        message: 'Failure',
        description: passwordResetFailureMsg,
        duration: 5.5
      });
    });
  };

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

  const printValidationMsg = key => {
    if (touched[key] && errors[key]) {
      return /*#__PURE__*/_react.default.createElement("div", {
        role: "alert",
        className: _SigninFormModule.default.SigninForm__signInContainer__formItem__error
      }, errors[key]);
    } else return null;
  };

  const handleForgotScreenToogle = value => {
    setPaswordResetEmailSendStatus(value);

    if (!value) {
      setMessage(_objectSpread(_objectSpread({}, message), {}, {
        success: null,
        error: null
      }));
    }

    resetForm();
  };

  return /*#__PURE__*/_react.default.createElement("div", {
    className: _SigninFormModule.default.SigninForm,
    "data-testid": "sign-in-form"
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: _SigninFormModule.default.SigninForm__signInContainer
  }, /*#__PURE__*/_react.default.createElement("h3", {
    "data-testid": "SigninForm_heading"
  }, isForgotPasswordPage && !isResetPasswordPage ? "Send reset password link" : !isForgotPasswordPage && isResetPasswordPage ? "Reset your Password" : "Great to have you here!"), /*#__PURE__*/_react.default.createElement("form", {
    onSubmit: handleSubmit
  }, /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SigninFormModule.default.SigninForm__signInContainer__formItem,
    label: "Enter email address",
    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"
  }), printValidationMsg("email")), !isForgotPasswordPage ? /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SigninFormModule.default.SigninForm__signInContainer__formItem,
    label: !isResetPasswordPage ? "Enter the Password" : "Enter new 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"
  }), printValidationMsg("password")) : null, isResetPasswordPage ? /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SigninFormModule.default.SigninForm__signInContainer__formItem,
    label: "Renter the password",
    name: "passwordConfirmation",
    validateStatus: handleValidationStatus("passwordConfirmation"),
    hasFeedback: true
  }, /*#__PURE__*/_react.default.createElement(_antd.Input.Password, {
    id: "passwordConfirmation",
    name: "passwordConfirmation",
    type: "text",
    onChange: handleChange,
    onBlur: handleBlur,
    value: values.passwordConfirmation,
    placeholder: "Reenter password"
  }), printValidationMsg("passwordConfirmation")) : null, !isResetPasswordPage ? /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SigninFormModule.default.SigninForm__signInContainer__formItem
  }, !isForgotPasswordPage ? /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    name: "remember",
    valuePropName: "checked",
    noStyle: true
  }, /*#__PURE__*/_react.default.createElement(_antd.Checkbox, null, "Remember me")) : null, !isForgotPasswordPage ? /*#__PURE__*/_react.default.createElement(_reactRouterDom.Link, {
    to: "/forgot-password"
  }, "Forgot password") : null) : null, /*#__PURE__*/_react.default.createElement("div", {
    className: !isForgotPasswordPage ? _SigninFormModule.default.SigninForm__signInContainer__btnContainer : _SigninFormModule.default.SigninForm__signInContainer__btn_pwd_link
  }, /*#__PURE__*/_react.default.createElement(_antd.Button, {
    style: {
      background: background,
      color: textColor
    },
    loading: loading,
    htmlType: "submit"
  }, isForgotPasswordPage && !isResetPasswordPage ? "Submit" : !isForgotPasswordPage && isResetPasswordPage ? "Reset Password" : label, /*#__PURE__*/_react.default.createElement("span", null, /*#__PURE__*/_react.default.createElement(_reactFontawesome.FontAwesomeIcon, {
    icon: _freeRegularSvgIcons.faArrowAltCircleRight
  })))), !isForgotPasswordPage && !isResetPasswordPage ? /*#__PURE__*/_react.default.createElement("div", {
    className: _SigninFormModule.default.SigninForm__signInContainer__helpMsg
  }, "Not yet registered? ", /*#__PURE__*/_react.default.createElement("a", {
    onClick: () => navigate("/signup")
  }, "Create an account")) : null, isAuthenticate === false && message.error !== null ? /*#__PURE__*/_react.default.createElement("div", {
    className: _SigninFormModule.default.SigninForm__alert
  }, /*#__PURE__*/_react.default.createElement(_antd.Alert, {
    message: message.error.title,
    description: message.error.description,
    type: message.error.type,
    showIcon: message.error.showIcon
  })) : null, /*#__PURE__*/_react.default.createElement("div", {
    className: _SigninFormModule.default.SigninForm__message_container
  }, isPaswordResetEmailSend ? message.success !== null ? /*#__PURE__*/_react.default.createElement(_antd.Alert, {
    message: message.success.title,
    description: message.success.description,
    type: message.success.type,
    showIcon: message.success.showIcon
  }) : message.error !== null ? /*#__PURE__*/_react.default.createElement(_antd.Alert, {
    message: message.error.title,
    description: message.error.description,
    type: message.error.type,
    showIcon: message.error.showIcon
  }) : null : null))), isForgotPasswordPage ? /*#__PURE__*/_react.default.createElement("div", {
    className: _SigninFormModule.default.SigninForm__btn_back_container
  }, /*#__PURE__*/_react.default.createElement(_reactRouterDom.Link, {
    to: "/"
  }, "Back To Login")) : null);
};

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