"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.RegisterForm = void 0;

var _taggedTemplateLiteralLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/taggedTemplateLiteralLoose"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

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

var _styledComponents = _interopRequireDefault(require("styled-components"));

var _router = require("next/router");

var _reactHookForm = require("react-hook-form");

var _lib = require("@sentecacommerce-theme/lib");

var _ = require("../../");

var _Checkbox = require("../../Common/Modals/AuthPopup/Components/Checkbox");

var _templateObject, _templateObject2, _templateObject3, _templateObject4;

var RegisterForm = function RegisterForm() {
  var _useGlobalLabels = (0, _lib.useGlobalLabels)(),
      commonMessages = _useGlobalLabels.commonMessages,
      forms = _useGlobalLabels.forms,
      buttons = _useGlobalLabels.buttons,
      errorMessages = _useGlobalLabels.errorMessages;

  var router = (0, _router.useRouter)();

  var _useReleva = (0, _lib.useReleva)(),
      firstSession = _useReleva.firstSession;

  var onSuccessfulReg = function onSuccessfulReg() {
    accept(control.getValues().email);
    firstSession();
    router.push('/');
  }; // Using test instead of mutate, just to see


  var _useRegister = (0, _lib.useRegister)({
    onSuccess: onSuccessfulReg
  }),
      mutate = _useRegister[0],
      error = _useRegister[1].error;

  var onSubmit = /*#__PURE__*/function () {
    var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(_ref) {
      var email, password;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              email = _ref.email, password = _ref.password;
              mutate({
                email: email,
                password: password
              });

            case 2:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function onSubmit(_x) {
      return _ref2.apply(this, arguments);
    };
  }();

  var _useAcceptOnRegister = (0, _lib.useAcceptOnRegister)({}),
      accept = _useAcceptOnRegister.accept,
      isAllFetching = _useAcceptOnRegister.isAllFetching,
      allSubscriptions = _useAcceptOnRegister.allSubscriptions,
      checkedSubs = _useAcceptOnRegister.checkedSubs,
      clickSub = _useAcceptOnRegister.clickSub,
      checkRequiredSubs = _useAcceptOnRegister.checkRequiredSubs;

  var _useForm = (0, _reactHookForm.useForm)({
    defaultValues: {
      email: '',
      password: '',
      passwordConfirm: ''
    },
    mode: 'onChange'
  }),
      control = _useForm.control,
      errors = _useForm.errors,
      formState = _useForm.formState,
      clearErrors = _useForm.clearErrors,
      setError = _useForm.setError,
      handleSubmit = _useForm.handleSubmit;

  var password = (0, _reactHookForm.useWatch)({
    control: control,
    name: 'password',
    defaultValue: ''
  });
  var passwordConfirm = (0, _reactHookForm.useWatch)({
    control: control,
    name: 'passwordConfirm',
    defaultValue: ''
  });
  var hasErrors = !!Object.keys(errors).length;
  var disabledButton = hasErrors || !checkRequiredSubs();
  /* eslint-disable */

  var apiErrors = (0, _lib.useErrors)(error, {
    email_unavailable: errorMessages.emailAlreadyRegistered
  });
  /* eslint-enable */

  var validatePasswordMatch = function validatePasswordMatch(passwordConfirmVal) {
    return passwordConfirmVal === password ? undefined : forms.passwordNotMatching;
  };

  var onPasswordKeyUp = function onPasswordKeyUp() {
    if (!formState.isSubmitted) return;
    var passwordError = validatePasswordMatch(passwordConfirm);

    if (!passwordError) {
      clearErrors('passwordConfirm');
      return;
    }

    setError('passwordConfirm', {
      type: 'manual',
      message: passwordError
    });
  };

  return /*#__PURE__*/_react["default"].createElement("form", {
    onSubmit: handleSubmit(onSubmit)
  }, /*#__PURE__*/_react["default"].createElement(FormWrap, null, /*#__PURE__*/_react["default"].createElement(_.InputLabel, null, commonMessages.emailAddress, /*#__PURE__*/_react["default"].createElement(_reactHookForm.Controller, {
    control: control,
    name: "email",
    rules: {
      required: forms.requiredField,
      pattern: {
        value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
        message: forms.invalidEmail
      }
    },
    as: /*#__PURE__*/_react["default"].createElement(_.Input, {
      id: "register-email"
    })
  }), /*#__PURE__*/_react["default"].createElement(_.FormError, {
    errors: errors,
    fieldName: "email"
  })), /*#__PURE__*/_react["default"].createElement(PasswordWrap, null, /*#__PURE__*/_react["default"].createElement(_.InputLabel, {
    className: "mr-2"
  }, commonMessages.password, /*#__PURE__*/_react["default"].createElement(_reactHookForm.Controller, {
    control: control,
    name: "password",
    rules: {
      required: forms.requiredField,
      minLength: {
        value: 8,
        message: forms.passwordLength
      }
    },
    as: /*#__PURE__*/_react["default"].createElement(_.Input, {
      id: "register-pass",
      type: "password",
      onKeyUp: onPasswordKeyUp
    })
  }), /*#__PURE__*/_react["default"].createElement(_.FormError, {
    errors: errors,
    fieldName: "password"
  })), /*#__PURE__*/_react["default"].createElement(_.InputLabel, {
    className: "ml-2"
  }, forms.confirmPassword, /*#__PURE__*/_react["default"].createElement(_reactHookForm.Controller, {
    control: control,
    name: "passwordConfirm",
    rules: {
      required: forms.requiredField,
      validate: validatePasswordMatch
    },
    as: /*#__PURE__*/_react["default"].createElement(_.Input, {
      id: "register-pass-re",
      type: "password",
      onKeyUp: onPasswordKeyUp
    })
  }), /*#__PURE__*/_react["default"].createElement(_.FormError, {
    errors: errors,
    fieldName: "passwordConfirm"
  }))), /*#__PURE__*/_react["default"].createElement(_.FormError, {
    fieldName: "email_unavailable",
    errors: apiErrors
  }), !isAllFetching && allSubscriptions && Object.keys(allSubscriptions).map(function (subscription, index) {
    return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_Checkbox.Checkbox, {
      key: index,
      size: "tiny",
      isChecked: checkedSubs == null ? void 0 : checkedSubs[subscription],
      onChange: function onChange() {
        return clickSub(subscription);
      }
    }, allSubscriptions[subscription].label, allSubscriptions[subscription].isRequired && /*#__PURE__*/_react["default"].createElement(Required, null, "*")));
  })), /*#__PURE__*/_react["default"].createElement(ButtonWrap, null, /*#__PURE__*/_react["default"].createElement(_.Button, {
    iconPosition: "right",
    icon: /*#__PURE__*/_react["default"].createElement(_.LockIcon, null),
    fullWidth: true,
    variant: disabledButton ? 'disabled' : 'primary',
    disabled: disabledButton
  }, buttons.register)));
};

exports.RegisterForm = RegisterForm;

var FormWrap = _styledComponents["default"].div(_templateObject || (_templateObject = (0, _taggedTemplateLiteralLoose2["default"])(["\n  min-height: 32rem;\n"])));

var PasswordWrap = _styledComponents["default"].div.attrs({
  className: 'd-flex f-row justify-content-between'
})(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  label {\n    width: 100%;\n  }\n"])));

var ButtonWrap = _styledComponents["default"].div.attrs({
  className: 'd-flex justify-content-center justify-content-lg-end'
})(_templateObject3 || (_templateObject3 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  width: 100%;\n  padding-top: 1rem;\n\n  button {\n    max-width: 27.3rem;\n  }\n"])));

var Required = _styledComponents["default"].sup.attrs({
  className: 'ml-1'
})(_templateObject4 || (_templateObject4 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  color: red;\n  font-size: 1.8rem;\n  line-height: initial;\n"])));
//# sourceMappingURL=index.js.map