import { useFormikContext } from 'formik';
import { toLabelAndValue, _findBy, notEquals, slugify } from '@bigbinary/neeto-cist';
import { PLURAL, SINGULAR } from '@bigbinary/neeto-commons-frontend/constants';
import { globalProps } from '@bigbinary/neeto-commons-frontend/initializers';
import Button from '@bigbinary/neetoui/Button';
import Label from '@bigbinary/neetoui/Label';
import Radio from '@bigbinary/neetoui/formik/Radio';
import { prop, isNotNil, isNil, keys, pick, move, pluck, includes, equals, identical } from 'ramda';
import { Trans, useTranslation } from 'react-i18next';
import { n } from './inject-css-C2dztUxs.js';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import { t } from 'i18next';
import { dayjs } from '@bigbinary/neeto-commons-frontend/utils';
import * as yup from 'yup';
import { A as ADMIN_ROLES, c as ADMIN_ROLE_NAME } from './constants-CXdiW8NZ.js';
import Pane from '@bigbinary/neetoui/Pane';
import Modal from '@bigbinary/neetoui/Modal';
import { jsx, jsxs } from 'react/jsx-runtime';

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(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(_ref, _excluded$1);
  return /*#__PURE__*/jsx("div", _objectSpread$1(_objectSpread$1({
    className: className
  }, otherProps), {}, {
    children: children
  }));
};
var Page = function Page(_ref2) {
  var className = _ref2.className,
    children = _ref2.children,
    otherProps = _objectWithoutProperties(_ref2, _excluded2$1);
  return /*#__PURE__*/jsx("div", _objectSpread$1(_objectSpread$1({
    className: className
  }, otherProps), {}, {
    children: children
  }));
};
Page.Header = PageWrapper;
Page.Body = PageWrapper;
Page.Footer = PageWrapper;

var _globalProps$organiza$1;
var NAME_INPUT_VALIDATION_SCHEMA = {
  firstName: yup.string().trim(t("neetoTeamMembers.validations.removeSpaces")).strict(true),
  lastName: yup.string().trim(t("neetoTeamMembers.validations.removeSpaces")).strict(true)
};
var ROLES_RADIO_GROUP_VALIDATION_SCHEMA = {
  role: yup.string().required(t("neetoTeamMembers.validations.roleRequired"))
};
var APP_ROLES_SCHEMA = {
  appsRoles: yup.array().of(yup.object().shape({
    appName: yup.string(),
    isEnabled: yup["boolean"](),
    role: yup.string().required(t("neetoTeamMembers.validations.roleRequired"))
  }))
};
var FILTER_INVALID_EMAILS = {
  label: t("neetoTeamMembers.validations.filterInvalidEmails")
};
var COUNTER_PROPS = {
  label: t("neetoTeamMembers.common.email", PLURAL),
  startsFrom: 4
};
var DEFAULT_COMPONENT_CONFIG = {
  type: "pane",
  isOpen: false,
  className: "",
  headerProps: {},
  bodyProps: {},
  footerProps: {}
};
var MEMBERS_FORM_COMPONENT_MAPPER = {
  pane: Pane,
  modal: Modal,
  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 = 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(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 ? t("neetoTeamMembers.labels.neeto_", {
    product: activeAppRoles[0].appName
  }) : 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 = globalProps.appName) === null || _globalProps$appName === void 0 ? void 0 : _globalProps$appName.substring(5))) {
    return currentAppRole;
  }
  var condition = isAdminRole(currentAppRole);
  var role = _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 = globalProps.appName) === null || _globalProps$appName2 === void 0 ? void 0 : _globalProps$appName2.substring(5);
  var currentAppNameIndex = appNames.indexOf(currentApp);
  var appNamesSorted = 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 includes(role, ADMIN_ROLES) ? equals(ADMIN_ROLE_NAME) : notEquals(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 (isNotNil(selectedMember)) {
    var _memberShowData$membe;
    var keysToPick = ["firstName", "lastName", "role"].concat(_toConsumableArray(keys(additionalFieldsInitialValues)));
    return _objectSpread(_objectSpread(_objectSpread({}, additionalFieldsInitialValues), pick(keysToPick, selectedMember)), {}, {
      emails: [_objectSpread(_objectSpread({}, 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(_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(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(_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: 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.object().shape(_objectSpread(_objectSpread(_objectSpread(_objectSpread({}, NAME_INPUT_VALIDATION_SCHEMA), ROLES_RADIO_GROUP_VALIDATION_SCHEMA), APP_ROLES_SCHEMA), {}, {
    emails: yup.array().min(1, t("neetoTeamMembers.validations.minOneEmail")).test("are-all-emails-valid", function (_ref7) {
      var value = _ref7.value;
      return t("neetoTeamMembers.validations.validEmail", {
        count: value.length
      });
    }, function (emails) {
      return emails.every(prop("valid"));
    }).test("is-emails-length-within-available-members-capacity", /*#__PURE__*/jsx(Trans, {
      i18nKey: "neetoTeamMembers.validations.memberLimitExceeded",
      values: {
        limit: memberLimit
      },
      components: {
        emailTo: /*#__PURE__*/jsx(Button, {
          href: "mailto:support@neeto.com",
          style: "link"
        })
      }
    }), function (emails) {
      return isNotNil(selectedMember) || 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 = dayjs().startOf("day");
  var expiry = dayjs(expiryDate).startOf("day");
  return expiry.diff(today, "day");
};
"".concat((_globalProps$organiza = globalProps.organization) === null || _globalProps$organiza === void 0 ? void 0 : _globalProps$organiza.authAppUrl, "/settings/general/products");

var css = ".ntm-members-radio-group,.ntm-members-radio-group .neeto-ui-radio__container--stacked{width:100%}.ntm-members-radio-group__label{padding-inline-end:.25rem}.ntm-members-radio-group__icon{cursor:pointer}.ntm-members-form-radio-item__wrapper{cursor:pointer;padding:.5rem 0!important;width:100%}.ntm-members-form-radio-item__wrapper:first-child{padding-top:0!important}.ntm-members-form-radio-item__label{margin-bottom:0!important}.ntm-members-form-radio-item__description{color:rgb(var(--neeto-ui-gray-700))}\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3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3J0YW50O1xufVxuXG4ubnRtLW1lbWJlcnMtZm9ybS1yYWRpby1pdGVtX19kZXNjcmlwdGlvbiB7XG4gIGNvbG9yOiByZ2IodmFyKC0tbmVldG8tdWktZ3JheS03MDApKTtcbn1cbiJdfQ== */";
n(css,{});

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 = useTranslation(),
    t = _useTranslation.t;
  var _useFormikContext = 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 = 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 = _findBy({
        name: condition
      }, globalRoles[appName]);
      if (matchingRole) {
        setFieldValue("appRoles[".concat(index, "].activeRole"), matchingRole.name);
      }
    });
  };
  return /*#__PURE__*/jsx(Radio, {
    stacked: true,
    className: "ntm-members-radio-group grow-0",
    "data-testid": "ntm-manage-member-roles-group",
    labelProps: {
      className: "neeto-ui-radio__label w-full"
    },
    name: "role",
    label: /*#__PURE__*/jsxs("span", {
      className: "flex w-full items-center justify-between",
      children: [/*#__PURE__*/jsxs(Label, {
        required: true,
        children: [" ", t("neetoTeamMembers.common.role", SINGULAR)]
      }), /*#__PURE__*/jsx(Button, {
        label: t("neetoTeamMembers.labels.manageRole", PLURAL),
        style: "link",
        to: config.pathToRolesPage
      })]
    }),
    onChange: function onChange(_ref3) {
      var value = _ref3.target.value;
      setFieldValue("role", value);
      !isEdit && setDefaultSelection(value);
    },
    children: roles.map(function (_ref4) {
      var id = _ref4.id,
        name = _ref4.name;
      return /*#__PURE__*/jsx("label", {
        className: "ntm-members-form-radio-item__wrapper",
        htmlFor: slugify(name),
        children: /*#__PURE__*/jsx(Radio.Item, {
          className: "ntm-members-form-radio-item__label",
          "data-testid": "ntm-manage-member-roles-button",
          defaultChecked: identical(name, role),
          id: slugify(name),
          label: name,
          name: "role",
          value: name
        })
      }, id);
    })
  });
};

export { COUNTER_PROPS as C, DEFAULT_COMPONENT_CONFIG as D, EMAIL_REGEX as E, FORM_PAGES as F, MEMBERS_FORM_COMPONENT_MAPPER as M, NEETO_AUTH_MANAGE_PRODUCT_URL as N, RolesRadioGroup as R, getInviteURL as a, FILTER_INVALID_EMAILS as b, buildValidationSchema as c, renderInitialValues as d, renderPayload as e, getSingleInvitationTranslationProps as g, remainingExpiryDays as r };
//# sourceMappingURL=RolesRadioGroup-BusIs5tc.js.map
