import _taggedTemplateLiteralLoose from "@babel/runtime/helpers/taggedTemplateLiteralLoose";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";

var _templateObject, _templateObject2, _templateObject3, _templateObject4;

import React from 'react';
import styled from 'styled-components';
import { useRouter } from 'next/router';
import { useForm, Controller, useWatch } from 'react-hook-form';
import { useGlobalLabels, useRegister, useAcceptOnRegister, useErrors, useReleva } from '@sentecacommerce-theme/lib';
import { FormError, Button, LockIcon, Input, InputLabel as Label } from '../../';
import { Checkbox } from '../../Common/Modals/AuthPopup/Components/Checkbox';
export var RegisterForm = () => {
  var {
    commonMessages,
    forms,
    buttons,
    errorMessages
  } = useGlobalLabels();
  var router = useRouter();
  var {
    firstSession
  } = useReleva();

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


  var [mutate, {
    error
  }] = useRegister({
    onSuccess: onSuccessfulReg
  });

  var onSubmit = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator(function* (_ref) {
      var {
        email,
        password
      } = _ref;
      mutate({
        email,
        password
      });
    });

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

  var {
    accept,
    isAllFetching,
    allSubscriptions,
    checkedSubs,
    clickSub,
    checkRequiredSubs
  } = useAcceptOnRegister({});
  var {
    control,
    errors,
    formState,
    clearErrors,
    setError,
    handleSubmit
  } = useForm({
    defaultValues: {
      email: '',
      password: '',
      passwordConfirm: ''
    },
    mode: 'onChange'
  });
  var password = useWatch({
    control,
    name: 'password',
    defaultValue: ''
  });
  var passwordConfirm = useWatch({
    control,
    name: 'passwordConfirm',
    defaultValue: ''
  });
  var hasErrors = !!Object.keys(errors).length;
  var disabledButton = hasErrors || !checkRequiredSubs();
  /* eslint-disable */

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

  var validatePasswordMatch = passwordConfirmVal => passwordConfirmVal === password ? undefined : forms.passwordNotMatching;

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

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

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

  return /*#__PURE__*/React.createElement("form", {
    onSubmit: handleSubmit(onSubmit)
  }, /*#__PURE__*/React.createElement(FormWrap, null, /*#__PURE__*/React.createElement(Label, null, commonMessages.emailAddress, /*#__PURE__*/React.createElement(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.createElement(Input, {
      id: "register-email"
    })
  }), /*#__PURE__*/React.createElement(FormError, {
    errors: errors,
    fieldName: "email"
  })), /*#__PURE__*/React.createElement(PasswordWrap, null, /*#__PURE__*/React.createElement(Label, {
    className: "mr-2"
  }, commonMessages.password, /*#__PURE__*/React.createElement(Controller, {
    control: control,
    name: "password",
    rules: {
      required: forms.requiredField,
      minLength: {
        value: 8,
        message: forms.passwordLength
      }
    },
    as: /*#__PURE__*/React.createElement(Input, {
      id: "register-pass",
      type: "password",
      onKeyUp: onPasswordKeyUp
    })
  }), /*#__PURE__*/React.createElement(FormError, {
    errors: errors,
    fieldName: "password"
  })), /*#__PURE__*/React.createElement(Label, {
    className: "ml-2"
  }, forms.confirmPassword, /*#__PURE__*/React.createElement(Controller, {
    control: control,
    name: "passwordConfirm",
    rules: {
      required: forms.requiredField,
      validate: validatePasswordMatch
    },
    as: /*#__PURE__*/React.createElement(Input, {
      id: "register-pass-re",
      type: "password",
      onKeyUp: onPasswordKeyUp
    })
  }), /*#__PURE__*/React.createElement(FormError, {
    errors: errors,
    fieldName: "passwordConfirm"
  }))), /*#__PURE__*/React.createElement(FormError, {
    fieldName: "email_unavailable",
    errors: apiErrors
  }), !isAllFetching && allSubscriptions && Object.keys(allSubscriptions).map((subscription, index) => {
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Checkbox, {
      key: index,
      size: "tiny",
      isChecked: checkedSubs == null ? void 0 : checkedSubs[subscription],
      onChange: () => clickSub(subscription)
    }, allSubscriptions[subscription].label, allSubscriptions[subscription].isRequired && /*#__PURE__*/React.createElement(Required, null, "*")));
  })), /*#__PURE__*/React.createElement(ButtonWrap, null, /*#__PURE__*/React.createElement(Button, {
    iconPosition: "right",
    icon: /*#__PURE__*/React.createElement(LockIcon, null),
    fullWidth: true,
    variant: disabledButton ? 'disabled' : 'primary',
    disabled: disabledButton
  }, buttons.register)));
};
var FormWrap = styled.div(_templateObject || (_templateObject = _taggedTemplateLiteralLoose(["\n  min-height: 32rem;\n"])));
var PasswordWrap = styled.div.attrs({
  className: 'd-flex f-row justify-content-between'
})(_templateObject2 || (_templateObject2 = _taggedTemplateLiteralLoose(["\n  label {\n    width: 100%;\n  }\n"])));
var ButtonWrap = styled.div.attrs({
  className: 'd-flex justify-content-center justify-content-lg-end'
})(_templateObject3 || (_templateObject3 = _taggedTemplateLiteralLoose(["\n  width: 100%;\n  padding-top: 1rem;\n\n  button {\n    max-width: 27.3rem;\n  }\n"])));
var Required = styled.sup.attrs({
  className: 'ml-1'
})(_templateObject4 || (_templateObject4 = _taggedTemplateLiteralLoose(["\n  color: red;\n  font-size: 1.8rem;\n  line-height: initial;\n"])));
//# sourceMappingURL=index.js.map