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

var _templateObject, _templateObject2;

/* eslint-disable @typescript-eslint/camelcase */
import React from 'react';
import styled from 'styled-components';
import { useForm, Controller, useWatch } from 'react-hook-form';
import { useRegister, useAcceptOnRegister, useGlobalLabels, useErrors, Html, useReleva } from '@sentecacommerce-theme/lib';
import { FormError, Button, Input, InputLabel as Label, LockIcon } from '../../../..';
import { Checkbox } from '../Checkbox';
import { CTA } from '../Styled';
import { SocialLogin } from '../SocialLogin';
export var RegisterForm = (_ref) => {
  var {
    handleClose
  } = _ref;
  var {
    buttons,
    commonMessages,
    forms,
    errorMessages
  } = useGlobalLabels();
  var {
    firstSession
  } = useReleva();

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

  var [mutate, {
    error
  }] = useRegister({
    onSuccess: onSuccessfulReg
  });
  var apiErrors = useErrors(error, {
    email_unavailable: errorMessages.emailAlreadyRegistered
  });
  var {
    accept,
    clickSub,
    allSubscriptions,
    isAllFetching,
    checkedSubs,
    checkRequiredSubs
  } = useAcceptOnRegister({}); // Sort subscriptions so the required ones are at the bottom

  var sortedSubscripitons = allSubscriptions && Object.keys(allSubscriptions).sort((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 = _asyncToGenerator(function* (_ref2) {
      var {
        email,
        password
      } = _ref2;
      mutate({
        email,
        password
      });
    });

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

  var {
    handleSubmit,
    errors,
    control,
    setError,
    clearErrors,
    formState
  } = useForm({
    defaultValues: {
      email: '',
      password: '',
      passwordConfirm: ''
    },
    mode: 'onChange'
  });
  var hasErrors = !!Object.keys(errors).length;
  var password = useWatch({
    control,
    name: 'password',
    defaultValue: ''
  });
  var passwordConfirm = useWatch({
    control,
    name: 'passwordConfirm',
    defaultValue: ''
  });

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

  var disabledButton = hasErrors || !checkRequiredSubs();
  return /*#__PURE__*/React.createElement("form", {
    onSubmit: handleSubmit(onSubmit)
  }, /*#__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(Label, null, 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, null, forms.confirmPassword, /*#__PURE__*/React.createElement(Controller, {
    control: control,
    name: "passwordConfirm",
    rules: {
      required: forms.requiredField,
      validate: validatePasswordMatch
    },
    onKeyUp: onPasswordKeyUp,
    as: /*#__PURE__*/React.createElement(Input, {
      id: "register-pass-re",
      type: "password"
    })
  }), /*#__PURE__*/React.createElement(FormError, {
    errors: errors,
    fieldName: "passwordConfirm"
  })), !isAllFetching && allSubscriptions && (sortedSubscripitons == null ? void 0 : sortedSubscripitons.map(sub => {
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Checkbox, {
      key: sub,
      isChecked: checkedSubs == null ? void 0 : checkedSubs[sub],
      onChange: () => clickSub(sub),
      size: "tiny",
      name: "" + (allSubscriptions[sub].isRequired && 'required_sub')
    }, /*#__PURE__*/React.createElement(GDPRLabel, null, /*#__PURE__*/React.createElement(Html, null, allSubscriptions == null ? void 0 : allSubscriptions[sub].description))), allSubscriptions[sub].isRequired && !(checkedSubs != null && checkedSubs[sub]) && /*#__PURE__*/React.createElement(Req, null, forms.requiredField));
  })), /*#__PURE__*/React.createElement(CTA, null, /*#__PURE__*/React.createElement(Button, {
    icon: /*#__PURE__*/React.createElement(LockIcon, null),
    iconPosition: "right",
    variant: disabledButton ? 'disabled' : 'primary',
    fullWidth: true,
    disabled: disabledButton
  }, buttons.register)), /*#__PURE__*/React.createElement(FormError, {
    fieldName: "email_unavailable",
    errors: apiErrors
  }), /*#__PURE__*/React.createElement(SocialLogin, {
    handleClose: handleClose
  }));
};
var Req = styled.p.attrs({
  className: 'ml-4 pt-1'
})(_templateObject || (_templateObject = _taggedTemplateLiteralLoose(["\n  color: ", ";\n  margin: -0.5rem 0 0.5rem 0;\n  font-size: 1.3rem;\n"])), (_ref4) => {
  var {
    theme
  } = _ref4;
  return theme.palette.danger;
});
var GDPRLabel = styled.span(_templateObject2 || (_templateObject2 = _taggedTemplateLiteralLoose(["\n  & > div {\n    & > a {\n      text-decoration: underline;\n    }\n  }\n"])));
//# sourceMappingURL=index.js.map