'use strict';

var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var React = require('react');
var neetoAtoms = require('@bigbinary/neeto-atoms');
var formik = require('@bigbinary/neeto-atoms/formik');
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/v2/ErrorPage');
var reactI18next = require('react-i18next');
var reactRouterDom = require('react-router-dom');
var constants = require('../../constants-CMNbKvoF.js');
var ActionBlock = require('../../ActionBlock-C9Iy0jGZ.js');
var Select = require('../../Select-CshPoN2b.js');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
require('@babel/runtime/helpers/objectWithoutProperties');
require('formik');
var jsxRuntime = require('react/jsx-runtime');
var axios = require('axios');
var i18next = require('i18next');
var constants$1 = require('@bigbinary/neeto-commons-frontend/constants');
var yup = require('yup');
var InviteLinkError = require('../../InviteLinkError-AphtWLhe.js');
var utils = require('@bigbinary/neeto-commons-frontend/utils');
require('ramda');

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 _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var axios__default = /*#__PURE__*/_interopDefault(axios);
var yup__namespace = /*#__PURE__*/_interopNamespace(yup);

var PageLoader = function PageLoader(_ref) {
  var className = _ref.className;
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: neetoAtoms.cn("flex h-full w-full items-center justify-center p-6", className),
    children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Spinner, {})
  });
};

// eslint-disable-next-line @bigbinary/neeto/no-axios-import-outside-apis
var showInviteLink = function showInviteLink(inviteToken) {
  return axios__default.default.get("".concat(constants.BASE_URL, "/public/invitations/").concat(inviteToken));
};
var createInvitation = function createInvitation(payload) {
  return axios__default.default.post("".concat(constants.BASE_URL, "/public/invitations"), payload);
};
var invitationsApi = {
  showInviteLink: showInviteLink,
  createInvitation: createInvitation
};

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var useShowInviteLink = function useShowInviteLink(inviteToken) {
  return reactQuery.useQuery({
    queryKey: [constants.QUERY_KEYS.INVITATION_LINK, inviteToken],
    queryFn: function queryFn() {
      return invitationsApi.showInviteLink(inviteToken);
    },
    enabled: !!inviteToken
  });
};
var useCreateInvitation = function useCreateInvitation() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return reactQuery.useMutation(_objectSpread({
    mutationFn: function mutationFn(payload) {
      return invitationsApi.createInvitation(payload);
    }
  }, options));
};

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$1.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 h-screen w-screen items-center justify-center bg-gray-50 px-4",
    children: /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "flex w-full max-w-2xl flex-col items-center justify-center space-y-4 text-center",
      children: [/*#__PURE__*/jsxRuntime.jsx("div", {
        className: "mb-4",
        children: /*#__PURE__*/jsxRuntime.jsx(InviteLinkError.SvgInviteLinkError, {
          size: 64
        })
      }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
        style: "h1",
        weight: "bold",
        children: isExpired ? t("neetoTeamMembers.alerts.messages.expiredTitle") : t("neetoTeamMembers.alerts.messages.domainTitle")
      }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
        className: "text-muted-foreground",
        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.isBefore(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 = 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.QUERY_KEYS.INVITATION_LINK, inviteId]
    });
    setIsSubmitting(false);
  };
  var _useCreateInvitation = 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, {})
    });
  }
  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 min-h-screen w-screen items-center justify-center bg-gray-50 px-4",
    children: /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "w-full max-w-md space-y-6 p-6 shadow-lg",
      children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "space-y-2 text-center",
        children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
          style: "h3",
          children: t("neetoTeamMembers.helpers.invitationTitle")
        }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
          className: "text-muted-foreground",
          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(Select.FormikForm, {
        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(formik.Input, {
              required: true,
              label: t("neetoTeamMembers.common.email_one"),
              name: "email",
              type: "email"
            }), /*#__PURE__*/jsxRuntime.jsx(ActionBlock.FormikActionBlock, {
              submitButtonProps: {
                label: t("neetoTeamMembers.buttons.acceptInvitation"),
                disabled: !isValid || !dirty
              }
            })]
          });
        }
      })]
    })
  });
};

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