'use strict';

var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var React = require('react');
var reactQuery = require('@tanstack/react-query');
var initializers = require('@bigbinary/neeto-commons-frontend/initializers');
var reactUtils = require('@bigbinary/neeto-commons-frontend/react-utils');
var ErrorPageGlobal = require('@bigbinary/neeto-molecules/ErrorPage');
var PageLoader = require('@bigbinary/neeto-molecules/PageLoader');
var Typography = require('@bigbinary/neetoui/Typography');
var Input = require('@bigbinary/neetoui/formik/Input');
var Form = require('@bigbinary/neetoui/formik/Form');
var ActionBlock = require('@bigbinary/neetoui/formik/ActionBlock');
var reactI18next = require('react-i18next');
var reactRouterDom = require('react-router-dom');
var InviteLinkError = require('../InviteLinkError-Chs1iVCJ.js');
var constants$1 = require('../constants-D_H6M1Pm.js');
var i18next = require('i18next');
var constants = require('@bigbinary/neeto-commons-frontend/constants');
var yup = require('yup');
var jsxRuntime = require('react/jsx-runtime');
var utils = require('@bigbinary/neeto-commons-frontend/utils');
require('@babel/runtime/helpers/defineProperty');
require('axios');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var ErrorPageGlobal__default = /*#__PURE__*/_interopDefault(ErrorPageGlobal);
var PageLoader__default = /*#__PURE__*/_interopDefault(PageLoader);
var Typography__default = /*#__PURE__*/_interopDefault(Typography);
var Input__default = /*#__PURE__*/_interopDefault(Input);
var Form__default = /*#__PURE__*/_interopDefault(Form);
var ActionBlock__default = /*#__PURE__*/_interopDefault(ActionBlock);
var yup__namespace = /*#__PURE__*/_interopNamespace(yup);

var VALIDATION_SCHEMA = yup__namespace.object().shape({
  email: yup__namespace.string().email(i18next.t("neetoTeamMembers.validations.validEmail_one")).required(i18next.t("neetoTeamMembers.validations.required", {
    what: i18next.t("neetoTeamMembers.common.email", constants.SINGULAR)
  }))
});
var ERROR = {
  EXPIRED: 410,
  INVALID_DOMAIN: 422
};
var ROOT_URL = "/";

var ErrorPage = reactUtils.withT(function (_ref) {
  var t = _ref.t,
    _ref$isExpired = _ref.isExpired,
    isExpired = _ref$isExpired === void 0 ? false : _ref$isExpired,
    _ref$email = _ref.email,
    email = _ref$email === void 0 ? "" : _ref$email,
    _ref$allowedDomain = _ref.allowedDomain,
    allowedDomain = _ref$allowedDomain === void 0 ? "" : _ref$allowedDomain;
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: "flex justify-center items-center min-h-screen bg-gray-50 px-4 h-screen w-screen",
    children: /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "w-full max-w-2xl text-center space-y-4 flex flex-col items-center justify-center",
      children: [/*#__PURE__*/jsxRuntime.jsx("div", {
        className: "mb-4",
        children: /*#__PURE__*/jsxRuntime.jsx(InviteLinkError.SvgInviteLinkError, {
          size: 64
        })
      }), /*#__PURE__*/jsxRuntime.jsx(Typography__default.default, {
        style: "h1",
        weight: "bold",
        children: isExpired ? t("neetoTeamMembers.alerts.messages.expiredTitle") : t("neetoTeamMembers.alerts.messages.domainTitle")
      }), /*#__PURE__*/jsxRuntime.jsx(Typography__default.default, {
        className: "neeto-ui-text-gray-600",
        children: isExpired ? t("neetoTeamMembers.alerts.messages.expiredMessage") : /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
          components: {
            strong: /*#__PURE__*/jsxRuntime.jsx("strong", {})
          },
          i18nKey: "neetoTeamMembers.alerts.messages.domainMessage",
          values: {
            allowedDomain: allowedDomain,
            email: email
          }
        })
      })]
    })
  });
});

var getStartOfDay = function getStartOfDay(date) {
  return utils.dayjs(date).startOf("day");
};
var isExpired = function isExpired(date) {
  if (!date) return false;
  var today = getStartOfDay();
  var expiryDate = getStartOfDay(date);
  return expiryDate.isSameOrBefore(today);
};

var MembersInvite = function MembersInvite() {
  var queryClient = reactQuery.useQueryClient();
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useParams = reactRouterDom.useParams(),
    inviteId = _useParams.inviteId;
  var displayErrorPage = reactUtils.useDisplayErrorPage();
  var _useState = React.useState(false),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    isSubmitting = _useState2[0],
    setIsSubmitting = _useState2[1];
  var _useShowInviteLink = InviteLinkError.useShowInviteLink(inviteId),
    inviteLink = _useShowInviteLink.data,
    isLoading = _useShowInviteLink.isLoading;
  var handleSuccess = function handleSuccess(response) {
    if (response !== null && response !== void 0 && response.redirectUrl) {
      window.location.href = response.redirectUrl;
    } else {
      setIsSubmitting(false);
    }
  };
  var handleError = function handleError() {
    queryClient.invalidateQueries({
      queryKey: [constants$1.QUERY_KEYS.INVITATION_LINK, inviteId]
    });
    setIsSubmitting(false);
  };
  var _useCreateInvitation = InviteLinkError.useCreateInvitation({
      onSuccess: handleSuccess,
      onError: handleError
    }),
    createInvitation = _useCreateInvitation.mutate,
    isError = _useCreateInvitation.isError,
    error = _useCreateInvitation.error,
    variables = _useCreateInvitation.variables;
  var isInviteExpired = isExpired(inviteLink === null || inviteLink === void 0 ? void 0 : inviteLink.expiresAt) || isError && (error === null || error === void 0 ? void 0 : error.status) === ERROR.EXPIRED;
  var isInvalidDomain = isError && (error === null || error === void 0 ? void 0 : error.status) === ERROR.INVALID_DOMAIN;
  var handleSubmit = function handleSubmit(_ref) {
    var email = _ref.email;
    setIsSubmitting(true);
    return createInvitation({
      email: email,
      inviteToken: inviteId
    });
  };
  if (isLoading || isSubmitting) {
    return /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "h-screen w-screen",
      children: /*#__PURE__*/jsxRuntime.jsx(PageLoader__default.default, {})
    });
  }
  if (isInviteExpired || isInvalidDomain) {
    return /*#__PURE__*/jsxRuntime.jsx(ErrorPage, {
      allowedDomain: inviteLink === null || inviteLink === void 0 ? void 0 : inviteLink.domain,
      email: variables === null || variables === void 0 ? void 0 : variables.email,
      isExpired: isInviteExpired
    });
  }
  if (displayErrorPage) {
    return /*#__PURE__*/jsxRuntime.jsx(ErrorPageGlobal__default.default, {
      homeUrl: ROOT_URL
    });
  }
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: "flex justify-center items-center min-h-screen bg-gray-50 px-4 w-screen",
    children: /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "w-full max-w-md p-6 space-y-6 neeto-ui-shadow-lg",
      children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "text-center space-y-2",
        children: [/*#__PURE__*/jsxRuntime.jsx(Typography__default.default, {
          style: "h3",
          children: t("neetoTeamMembers.helpers.invitationTitle")
        }), /*#__PURE__*/jsxRuntime.jsx(Typography__default.default, {
          className: "neeto-ui-text-gray-600",
          style: "body2",
          children: /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
            components: {
              strong: /*#__PURE__*/jsxRuntime.jsx("strong", {})
            },
            i18nKey: "neetoTeamMembers.helpers.invitationMessage",
            values: {
              organization: initializers.globalProps.organization.name
            }
          })
        })]
      }), /*#__PURE__*/jsxRuntime.jsx(Form__default.default, {
        formikProps: {
          initialValues: {
            email: ""
          },
          validationSchema: VALIDATION_SCHEMA,
          onSubmit: handleSubmit
        },
        children: function children(_ref2) {
          var isValid = _ref2.isValid,
            dirty = _ref2.dirty;
          return /*#__PURE__*/jsxRuntime.jsxs("div", {
            className: "space-y-4",
            children: [/*#__PURE__*/jsxRuntime.jsx(Input__default.default, {
              required: true,
              label: t("neetoTeamMembers.common.email_one"),
              name: "email",
              type: "email"
            }), /*#__PURE__*/jsxRuntime.jsx(ActionBlock__default.default, {
              submitButtonProps: {
                label: t("neetoTeamMembers.buttons.acceptInvitation"),
                disabled: !isValid || !dirty
              }
            })]
          });
        }
      })]
    })
  });
};

module.exports = MembersInvite;
//# sourceMappingURL=MembersInvite.js.map
