"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 _reactHookForm = require("react-hook-form");

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

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

var _Checkbox = require("../Checkbox");

var _Styled = require("../Styled");

var _SocialLogin = require("../SocialLogin");

var _templateObject, _templateObject2;

var RegisterForm = function RegisterForm(_ref) {
  var handleClose = _ref.handleClose;

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

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

  var onSuccessfulReg = function onSuccessfulReg() {
    accept(control.getValues().email);
    firstSession();
    handleClose();
  };

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

  var apiErrors = (0, _lib.useErrors)(error, {
    email_unavailable: errorMessages.emailAlreadyRegistered
  });

  var _useAcceptOnRegister = (0, _lib.useAcceptOnRegister)({}),
      accept = _useAcceptOnRegister.accept,
      clickSub = _useAcceptOnRegister.clickSub,
      allSubscriptions = _useAcceptOnRegister.allSubscriptions,
      isAllFetching = _useAcceptOnRegister.isAllFetching,
      checkedSubs = _useAcceptOnRegister.checkedSubs,
      checkRequiredSubs = _useAcceptOnRegister.checkRequiredSubs; // Sort subscriptions so the required ones are at the bottom


  var sortedSubscripitons = allSubscriptions && Object.keys(allSubscriptions).sort(function (x, y) {
    var _allSubscriptions$x, _allSubscriptions$y, _allSubscriptions$x2;

    return (allSubscriptions == null ? void 0 : (_allSubscriptions$x = allSubscriptions[x]) == null ? void 0 : _allSubscriptions$x.isRequired) === (allSubscriptions == null ? void 0 : (_allSubscriptions$y = allSubscriptions[y]) == null ? void 0 : _allSubscriptions$y.isRequired) ? 0 : allSubscriptions != null && (_allSubscriptions$x2 = allSubscriptions[x]) != null && _allSubscriptions$x2.isRequired ? 1 : -1;
  });

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

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

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

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

  var hasErrors = !!Object.keys(errors).length;
  var password = (0, _reactHookForm.useWatch)({
    control: control,
    name: 'password',
    defaultValue: ''
  });
  var passwordConfirm = (0, _reactHookForm.useWatch)({
    control: control,
    name: 'passwordConfirm',
    defaultValue: ''
  });

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

  var disabledButton = hasErrors || !checkRequiredSubs();
  return /*#__PURE__*/_react["default"].createElement("form", {
    onSubmit: handleSubmit(onSubmit)
  }, /*#__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(_.InputLabel, null, 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, null, forms.confirmPassword, /*#__PURE__*/_react["default"].createElement(_reactHookForm.Controller, {
    control: control,
    name: "passwordConfirm",
    rules: {
      required: forms.requiredField,
      validate: validatePasswordMatch
    },
    onKeyUp: onPasswordKeyUp,
    as: /*#__PURE__*/_react["default"].createElement(_.Input, {
      id: "register-pass-re",
      type: "password"
    })
  }), /*#__PURE__*/_react["default"].createElement(_.FormError, {
    errors: errors,
    fieldName: "passwordConfirm"
  })), !isAllFetching && allSubscriptions && (sortedSubscripitons == null ? void 0 : sortedSubscripitons.map(function (sub) {
    return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_Checkbox.Checkbox, {
      key: sub,
      isChecked: checkedSubs == null ? void 0 : checkedSubs[sub],
      onChange: function onChange() {
        return clickSub(sub);
      },
      size: "tiny",
      name: "" + (allSubscriptions[sub].isRequired && 'required_sub')
    }, /*#__PURE__*/_react["default"].createElement(GDPRLabel, null, /*#__PURE__*/_react["default"].createElement(_lib.Html, null, allSubscriptions == null ? void 0 : allSubscriptions[sub].description))), allSubscriptions[sub].isRequired && !(checkedSubs != null && checkedSubs[sub]) && /*#__PURE__*/_react["default"].createElement(Req, null, forms.requiredField));
  })), /*#__PURE__*/_react["default"].createElement(_Styled.CTA, null, /*#__PURE__*/_react["default"].createElement(_.Button, {
    icon: /*#__PURE__*/_react["default"].createElement(_.LockIcon, null),
    iconPosition: "right",
    variant: disabledButton ? 'disabled' : 'primary',
    fullWidth: true,
    disabled: disabledButton
  }, buttons.register)), /*#__PURE__*/_react["default"].createElement(_.FormError, {
    fieldName: "email_unavailable",
    errors: apiErrors
  }), /*#__PURE__*/_react["default"].createElement(_SocialLogin.SocialLogin, {
    handleClose: handleClose
  }));
};

exports.RegisterForm = RegisterForm;

var Req = _styledComponents["default"].p.attrs({
  className: 'ml-4 pt-1'
})(_templateObject || (_templateObject = (0, _taggedTemplateLiteralLoose2["default"])(["\n  color: ", ";\n  margin: -0.5rem 0 0.5rem 0;\n  font-size: 1.3rem;\n"])), function (_ref4) {
  var theme = _ref4.theme;
  return theme.palette.danger;
});

var GDPRLabel = _styledComponents["default"].span(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  & > div {\n    & > a {\n      text-decoration: underline;\n    }\n  }\n"])));
//# sourceMappingURL=index.js.map