'use strict';

var neetoAtoms = require('@bigbinary/neeto-atoms');
var formik = require('formik');
var neetoCist = require('@bigbinary/neeto-cist');
var constants = require('@bigbinary/neeto-commons-frontend/v2/constants');
var initializers = require('@bigbinary/neeto-commons-frontend/v2/initializers');
var ramda = require('ramda');
var reactI18next = require('react-i18next');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var i18next = require('i18next');
var utils = require('@bigbinary/neeto-commons-frontend/v2/utils');
var yup = require('yup');
var constants$1 = require('./constants-D_H6M1Pm.js');
var jsxRuntime = require('react/jsx-runtime');
var Select = require('./Select-CshPoN2b.js');

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 _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
var yup__namespace = /*#__PURE__*/_interopNamespace(yup);

var _excluded$1 = ["className", "children"],
  _excluded2$1 = ["className", "children"];
function ownKeys$1(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$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var PageWrapper = function PageWrapper(_ref) {
  var className = _ref.className,
    children = _ref.children,
    otherProps = _objectWithoutProperties__default.default(_ref, _excluded$1);
  return /*#__PURE__*/jsxRuntime.jsx("div", _objectSpread$1(_objectSpread$1({}, _objectSpread$1({
    className: className
  }, otherProps)), {}, {
    children: children
  }));
};
var Page = function Page(_ref2) {
  var className = _ref2.className,
    children = _ref2.children,
    otherProps = _objectWithoutProperties__default.default(_ref2, _excluded2$1);
  return /*#__PURE__*/jsxRuntime.jsx("div", _objectSpread$1(_objectSpread$1({}, _objectSpread$1({
    className: className
  }, otherProps)), {}, {
    children: children
  }));
};
Page.Header = PageWrapper;
Page.Title = PageWrapper;
Page.Description = PageWrapper;
Page.Body = PageWrapper;
Page.Footer = PageWrapper;

var _globalProps$organiza$1;
var FEEDBACK_DURATION_MS = 2500;
var NAME_INPUT_VALIDATION_SCHEMA = {
  firstName: yup__namespace.string().trim(i18next.t("neetoTeamMembers.validations.removeSpaces")).strict(true),
  lastName: yup__namespace.string().trim(i18next.t("neetoTeamMembers.validations.removeSpaces")).strict(true)
};
var ROLES_RADIO_GROUP_VALIDATION_SCHEMA = {
  role: yup__namespace.string().required(i18next.t("neetoTeamMembers.validations.roleRequired"))
};
var APP_ROLES_SCHEMA = {
  appsRoles: yup__namespace.array().of(yup__namespace.object().shape({
    appName: yup__namespace.string(),
    isEnabled: yup__namespace["boolean"](),
    role: yup__namespace.string().required(i18next.t("neetoTeamMembers.validations.roleRequired"))
  }))
};
var FILTER_INVALID_EMAILS = {
  label: i18next.t("neetoTeamMembers.validations.filterInvalidEmails")
};
var COUNTER_PROPS = {
  label: i18next.t("neetoTeamMembers.common.email", constants.PLURAL),
  startsFrom: 4
};
var DEFAULT_COMPONENT_CONFIG = {
  type: "pane",
  isOpen: false,
  className: "",
  headerProps: {},
  bodyProps: {},
  footerProps: {}
};
var MEMBERS_FORM_COMPONENT_MAPPER = {
  pane: neetoAtoms.Sheet,
  modal: neetoAtoms.Dialog,
  page: Page
};
var FORM_PAGES = {
  MAIN: "main",
  APP_LIST: "appList",
  CONFIRMATION: "confirmation",
  INVITE_LINK: "inviteLink"
};
var EMAIL_REGEX = new RegExp("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}$", "i");
var NEETO_AUTH_MANAGE_PRODUCT_URL = "".concat((_globalProps$organiza$1 = initializers.globalProps.organization) === null || _globalProps$organiza$1 === void 0 ? void 0 : _globalProps$organiza$1.authAppUrl, "/admin/admin-panel/general/products");

var _globalProps$organiza;
var _excluded = ["appRoles", "emails", "firstName", "lastName", "role"],
  _excluded2 = ["timeZone", "dateFormat", "timeFormat", "countryId", "language", "phonenumber", "avatar"];
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 getProductName = function getProductName(activeAppRoles) {
  var _activeAppRoles$;
  return activeAppRoles !== null && activeAppRoles !== void 0 && (_activeAppRoles$ = activeAppRoles[0]) !== null && _activeAppRoles$ !== void 0 && _activeAppRoles$.appName ? i18next.t("neetoTeamMembers.labels.neeto_", {
    product: activeAppRoles[0].appName
  }) : initializers.globalProps.appName;
};
var getActiveRole = function getActiveRole(activeAppRoles, role) {
  var _activeAppRoles$2;
  return (activeAppRoles === null || activeAppRoles === void 0 || (_activeAppRoles$2 = activeAppRoles[0]) === null || _activeAppRoles$2 === void 0 ? void 0 : _activeAppRoles$2.activeRole) || role;
};
var getDefaultRole = function getDefaultRole(roles, currentAppRole, appName) {
  var _globalProps$appName;
  if (appName === ((_globalProps$appName = initializers.globalProps.appName) === null || _globalProps$appName === void 0 ? void 0 : _globalProps$appName.substring(5))) {
    return currentAppRole;
  }
  var condition = isAdminRole(currentAppRole);
  var role = neetoCist._findBy({
    name: condition
  }, roles);
  return role ? role.name : roles[0].name;
};
var generateAppsRolesInitialValue = function generateAppsRolesInitialValue(globalRoles, currentAppRole) {
  var _globalProps$appName2;
  if (!globalRoles) return [];
  var appNames = Object.keys(globalRoles);
  var currentApp = (_globalProps$appName2 = initializers.globalProps.appName) === null || _globalProps$appName2 === void 0 ? void 0 : _globalProps$appName2.substring(5);
  var currentAppNameIndex = appNames.indexOf(currentApp);
  var appNamesSorted = ramda.move(currentAppNameIndex, 0, appNames);
  return appNamesSorted.map(function (appName) {
    return {
      appName: appName,
      activeRole: getDefaultRole(globalRoles[appName], currentAppRole, appName),
      isEnabled: true,
      isPrimary: currentApp === appName
    };
  });
};
var isAdminRole = function isAdminRole(role) {
  return ramda.includes(role, constants$1.ADMIN_ROLES) ? ramda.equals(constants$1.ADMIN_ROLE_NAME) : neetoCist.notEquals(constants$1.ADMIN_ROLE_NAME);
};
var renderInitialValues = function renderInitialValues(_ref) {
  var _roles$1$name, _roles$, _roles$2;
  var _ref$additionalFields = _ref.additionalFieldsInitialValues,
    additionalFieldsInitialValues = _ref$additionalFields === void 0 ? {} : _ref$additionalFields,
    globalRoles = _ref.globalRoles,
    memberShowData = _ref.memberShowData,
    roles = _ref.roles,
    selectedMember = _ref.selectedMember;
  if (ramda.isNotNil(selectedMember)) {
    var _memberShowData$membe;
    var keysToPick = ["firstName", "lastName", "role"].concat(_toConsumableArray__default.default(ramda.keys(additionalFieldsInitialValues)));
    return _objectSpread(_objectSpread(_objectSpread({}, additionalFieldsInitialValues), ramda.pick(keysToPick, selectedMember)), {}, {
      emails: [_objectSpread(_objectSpread({}, neetoCist.toLabelAndValue(selectedMember.email)), {}, {
        valid: true
      })],
      timeZone: selectedMember.timeZone || "",
      dateFormat: selectedMember.dateFormat || "",
      timeFormat: selectedMember.timeFormat || "",
      countryId: (memberShowData === null || memberShowData === void 0 || (_memberShowData$membe = memberShowData.member) === null || _memberShowData$membe === void 0 ? void 0 : _memberShowData$membe.countryIdentifier) || selectedMember.countryIdentifier || "",
      language: selectedMember.language || "",
      phonenumber: selectedMember.phonenumber || "",
      avatar: {
        imageUrl: selectedMember.profileImageUrl || "",
        file: null
      }
    });
  }
  return _objectSpread({
    firstName: "",
    lastName: "",
    emails: [],
    role: (_roles$1$name = (_roles$ = roles[1]) === null || _roles$ === void 0 ? void 0 : _roles$.name) !== null && _roles$1$name !== void 0 ? _roles$1$name : "",
    appRoles: generateAppsRolesInitialValue(globalRoles, (_roles$2 = roles[1]) === null || _roles$2 === void 0 ? void 0 : _roles$2.name)
  }, additionalFieldsInitialValues);
};
var renderPayload = function renderPayload(_ref2) {
  var appRoles = _ref2.appRoles,
    emails = _ref2.emails,
    firstName = _ref2.firstName,
    lastName = _ref2.lastName,
    role = _ref2.role,
    otherValues = _objectWithoutProperties__default.default(_ref2, _excluded);
  var selectedMember = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  if (selectedMember) {
    var timeZone = otherValues.timeZone,
      dateFormat = otherValues.dateFormat,
      timeFormat = otherValues.timeFormat,
      countryId = otherValues.countryId,
      language = otherValues.language,
      phonenumber = otherValues.phonenumber,
      avatar = otherValues.avatar,
      rest = _objectWithoutProperties__default.default(otherValues, _excluded2);
    var payload = _objectSpread({
      active: true,
      firstName: firstName.trim(),
      lastName: lastName.trim(),
      organizationRole: role,
      email: emails[0].value
    }, rest);
    var profileFields = {
      timeZone: timeZone,
      dateFormat: dateFormat,
      timeFormat: timeFormat,
      countryIdentifier: countryId,
      language: language,
      phonenumber: phonenumber
    };
    var profile = Object.fromEntries(Object.entries(profileFields).filter(function (_ref3) {
      var _ref4 = _slicedToArray__default.default(_ref3, 2),
        v = _ref4[1];
      return v;
    }));
    if (Object.keys(profile).length > 0 || avatar !== null && avatar !== void 0 && avatar.file) {
      payload.profile = profile;
    }
    return payload;
  }
  return {
    user: _objectSpread({
      emails: ramda.pluck("value", emails),
      organizationRole: role,
      appRoles: appRoles
    }, otherValues)
  };
};
var getSingleInvitationTranslationProps = function getSingleInvitationTranslationProps(_ref5) {
  var activeAppRoles = _ref5.activeAppRoles,
    role = _ref5.role,
    selectedEmail = _ref5.selectedEmail;
  return {
    count: selectedEmail.length,
    emails: selectedEmail,
    product: getProductName(activeAppRoles),
    role: getActiveRole(activeAppRoles, role)
  };
};
var buildValidationSchema = function buildValidationSchema(_ref6) {
  var selectedMember = _ref6.selectedMember,
    memberLimit = _ref6.memberLimit,
    activeUsersCount = _ref6.activeUsersCount;
  return yup__namespace.object().shape(_objectSpread(_objectSpread(_objectSpread(_objectSpread({}, NAME_INPUT_VALIDATION_SCHEMA), ROLES_RADIO_GROUP_VALIDATION_SCHEMA), APP_ROLES_SCHEMA), {}, {
    emails: yup__namespace.array().min(1, i18next.t("neetoTeamMembers.validations.minOneEmail")).test("are-all-emails-valid", function (_ref7) {
      var value = _ref7.value;
      return i18next.t("neetoTeamMembers.validations.validEmail", {
        count: value.length
      });
    }, function (emails) {
      return emails.every(ramda.prop("valid"));
    }).test("is-emails-length-within-available-members-capacity", /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
      i18nKey: "neetoTeamMembers.validations.memberLimitExceeded",
      values: {
        limit: memberLimit
      },
      components: {
        emailTo: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
          asChild: true,
          variant: "link",
          children: /*#__PURE__*/jsxRuntime.jsx("a", {
            href: "mailto:support@neeto.com",
            children: "support"
          })
        })
      }
    }), function (emails) {
      return ramda.isNotNil(selectedMember) || ramda.isNil(memberLimit) || emails.length <= memberLimit - activeUsersCount;
    }).nullable()
  }));
};
var getInviteURL = function getInviteURL(inviteToken) {
  return "".concat(window.location.origin, "/invite-link/").concat(inviteToken);
};
var remainingExpiryDays = function remainingExpiryDays(expiryDate) {
  var today = utils.dayjs().startOf("day");
  var expiry = utils.dayjs(expiryDate).startOf("day");
  return expiry.diff(today, "day");
};
"".concat((_globalProps$organiza = initializers.globalProps.organization) === null || _globalProps$organiza === void 0 ? void 0 : _globalProps$organiza.authAppUrl, "/settings/general/products");

var RolesRadioGroup = function RolesRadioGroup(_ref) {
  var config = _ref.config,
    globalRoles = _ref.globalRoles,
    isEdit = _ref.isEdit,
    _ref$role = _ref.role,
    role = _ref$role === void 0 ? "" : _ref$role,
    _ref$roles = _ref.roles,
    roles = _ref$roles === void 0 ? [] : _ref$roles;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useFormikContext = formik.useFormikContext(),
    values = _useFormikContext.values,
    setFieldValue = _useFormikContext.setFieldValue;
  var setDefaultSelection = function setDefaultSelection(currentRole) {
    var _values$appRoles;
    var condition = isAdminRole(currentRole);
    (_values$appRoles = values.appRoles) === null || _values$appRoles === void 0 || _values$appRoles.forEach(function (_ref2, index) {
      var _globalProps$appName;
      var appName = _ref2.appName,
        activeRole = _ref2.activeRole;
      if (appName === ((_globalProps$appName = initializers.globalProps.appName) === null || _globalProps$appName === void 0 ? void 0 : _globalProps$appName.substring(5))) {
        setFieldValue("appRoles[".concat(index, "].activeRole"), currentRole);
        return;
      }
      if (condition(activeRole)) return;
      var matchingRole = neetoCist._findBy({
        name: condition
      }, globalRoles[appName]);
      if (matchingRole) {
        setFieldValue("appRoles[".concat(index, "].activeRole"), matchingRole.name);
      }
    });
  };
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "space-y-2",
    children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "flex w-full items-center justify-between",
      children: [/*#__PURE__*/jsxRuntime.jsxs(neetoAtoms.Label, {
        children: [t("neetoTeamMembers.common.role", constants.SINGULAR), /*#__PURE__*/jsxRuntime.jsx("span", {
          className: "text-destructive",
          children: " *"
        })]
      }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
        asChild: true,
        variant: "link",
        children: /*#__PURE__*/jsxRuntime.jsx("a", {
          href: config.pathToRolesPage,
          children: t("neetoTeamMembers.labels.manageRole", constants.PLURAL)
        })
      })]
    }), /*#__PURE__*/jsxRuntime.jsx(Select.FormikRadioGroup, {
      stacked: true,
      className: "w-full grow-0",
      "data-testid": "ntm-manage-member-roles-group",
      name: "role",
      onChange: function onChange(_ref3) {
        var value = _ref3.target.value;
        setFieldValue("role", value);
        if (!isEdit) setDefaultSelection(value);
      },
      children: roles.map(function (_ref4) {
        var id = _ref4.id,
          name = _ref4.name;
        return /*#__PURE__*/jsxRuntime.jsx("label", {
          className: "w-full cursor-pointer py-1 first:pt-0",
          htmlFor: neetoCist.slugify(name),
          children: /*#__PURE__*/jsxRuntime.jsx(Select.FormikRadioGroup.Item, {
            "data-testid": "ntm-manage-member-roles-button",
            defaultChecked: ramda.identical(name, role),
            id: neetoCist.slugify(name),
            label: name,
            value: name
          })
        }, id);
      })
    })]
  });
};

exports.COUNTER_PROPS = COUNTER_PROPS;
exports.DEFAULT_COMPONENT_CONFIG = DEFAULT_COMPONENT_CONFIG;
exports.EMAIL_REGEX = EMAIL_REGEX;
exports.FEEDBACK_DURATION_MS = FEEDBACK_DURATION_MS;
exports.FILTER_INVALID_EMAILS = FILTER_INVALID_EMAILS;
exports.FORM_PAGES = FORM_PAGES;
exports.MEMBERS_FORM_COMPONENT_MAPPER = MEMBERS_FORM_COMPONENT_MAPPER;
exports.NEETO_AUTH_MANAGE_PRODUCT_URL = NEETO_AUTH_MANAGE_PRODUCT_URL;
exports.RolesRadioGroup = RolesRadioGroup;
exports.buildValidationSchema = buildValidationSchema;
exports.getInviteURL = getInviteURL;
exports.getSingleInvitationTranslationProps = getSingleInvitationTranslationProps;
exports.remainingExpiryDays = remainingExpiryDays;
exports.renderInitialValues = renderInitialValues;
exports.renderPayload = renderPayload;
//# sourceMappingURL=RolesRadioGroup-BsARnjvF.js.map
