'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var React = require('react');
var constants = require('@bigbinary/neeto-commons-frontend/constants');
var initializers = require('@bigbinary/neeto-commons-frontend/initializers');
var reactUtils = require('@bigbinary/neeto-commons-frontend/react-utils');
var utils$1 = require('@bigbinary/neeto-commons-frontend/utils');
var FiltersBar = require('@bigbinary/neeto-filters-frontend/Bar');
var Columns = require('@bigbinary/neeto-molecules/Columns');
var Container = require('@bigbinary/neeto-molecules/Container');
var SubHeader$1 = require('@bigbinary/neeto-molecules/SubHeader');
var TableWrapper = require('@bigbinary/neeto-molecules/TableWrapper');
var Alert = require('@bigbinary/neetoui/Alert');
var NoData = require('@bigbinary/neetoui/NoData');
var Table = require('@bigbinary/neetoui/Table');
var Spinner = require('@bigbinary/neetoui/Spinner');
var ramda = require('ramda');
var reactI18next = require('react-i18next');
var reactRouterDom = require('react-router-dom');
var withReactQuery = require('../withReactQuery-aLDu0h78.js');
var useRolesApi = require('../useRolesApi-DuL4eCuF.js');
var useTeamsApi = require('../useTeamsApi-ClWGPxNW.js');
var constants$1 = require('./constants.js');
var useTeams = require('../useTeams-C9N2TJY-.js');
var injectCss = require('../inject-css-B6qYtOJe.js');
var neetoCist = require('@bigbinary/neeto-cist');
var Button = require('@bigbinary/neetoui/Button');
var Tooltip = require('@bigbinary/neetoui/Tooltip');
var i18next = require('i18next');
var jsxRuntime = require('react/jsx-runtime');
var Dropdown = require('@bigbinary/neetoui/Dropdown');
var Typography = require('@bigbinary/neetoui/Typography');
var Right$1 = require('@bigbinary/neeto-icons/Right');
var NeetoUISearchIcon = require('@bigbinary/neeto-icons/Search');
var Input = require('@bigbinary/neetoui/Input');
var utils = require('../utils-CgwJI9pk.js');
var Pane = require('@bigbinary/neetoui/Pane');
var Radio = require('@bigbinary/neetoui/Radio');
var Toastr = require('@bigbinary/neetoui/Toastr');
var NeetoHeader = require('@bigbinary/neeto-molecules/Header');
var ManageMember = require('./ManageMember.js');
require('@tanstack/react-query');
require('../queryClient-4vAFE3bx.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('axios');
require('../constants-D_H6M1Pm.js');
require('qs');
require('@babel/runtime/helpers/toConsumableArray');
require('@bigbinary/neeto-filters-frontend/utils');
require('@bigbinary/neeto-molecules/MoreDropdown');
require('@bigbinary/neetoui/Avatar');
require('@babel/runtime/helpers/asyncToGenerator');
require('@babel/runtime/regenerator');
require('classnames');
require('@bigbinary/neeto-icons/Info');
require('@bigbinary/neeto-icons/LeftArrow');
require('@bigbinary/neeto-image-uploader-frontend/hooks');
require('@bigbinary/neetoui/Callout');
require('@bigbinary/neetoui/formik/ActionBlock');
require('@bigbinary/neetoui/formik/Form');
require('../index-4wQ9Y7v9.js');
require('formik');
require('../ProfileImage-DN5IzFz7.js');
require('../useCountriesApi-CjhrbnjK.js');
require('@bigbinary/neeto-icons/Edit');
require('@bigbinary/neeto-molecules/PhoneNumber');
require('yup');
require('@bigbinary/neetoui/Checkbox');
require('@bigbinary/neetoui/formik/Select');
require('@bigbinary/neetoui/formik/Switch');
require('../RolesRadioGroup-DsIpgIDf.js');
require('@bigbinary/neetoui/Label');
require('@bigbinary/neetoui/formik/Radio');
require('@bigbinary/neetoui/Modal');
require('@bigbinary/neeto-icons/MenuHorizontal');
require('@bigbinary/neeto-molecules/CopyToClipboardButton');
require('../useInviteLinksApi-COVfmZiQ.js');
require('@bigbinary/neetoui/formik/MultiEmailInput');
require('@bigbinary/neetoui/formik/Input');
require('./utils.js');
require('../_commonjsHelpers-BJu3ubxk.js');
require('@bigbinary/neeto-time-zones');

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

var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var FiltersBar__default = /*#__PURE__*/_interopDefault(FiltersBar);
var Container__default = /*#__PURE__*/_interopDefault(Container);
var SubHeader__default = /*#__PURE__*/_interopDefault(SubHeader$1);
var TableWrapper__default = /*#__PURE__*/_interopDefault(TableWrapper);
var Alert__default = /*#__PURE__*/_interopDefault(Alert);
var NoData__default = /*#__PURE__*/_interopDefault(NoData);
var Table__default = /*#__PURE__*/_interopDefault(Table);
var Spinner__default = /*#__PURE__*/_interopDefault(Spinner);
var Button__default = /*#__PURE__*/_interopDefault(Button);
var Tooltip__default = /*#__PURE__*/_interopDefault(Tooltip);
var Dropdown__default = /*#__PURE__*/_interopDefault(Dropdown);
var Typography__default = /*#__PURE__*/_interopDefault(Typography);
var Right__default = /*#__PURE__*/_interopDefault(Right$1);
var NeetoUISearchIcon__default = /*#__PURE__*/_interopDefault(NeetoUISearchIcon);
var Input__default = /*#__PURE__*/_interopDefault(Input);
var Pane__default = /*#__PURE__*/_interopDefault(Pane);
var Radio__default = /*#__PURE__*/_interopDefault(Radio);
var Toastr__default = /*#__PURE__*/_interopDefault(Toastr);
var NeetoHeader__default = /*#__PURE__*/_interopDefault(NeetoHeader);

var css = ".ntm-manage-members__header{align-items:flex-start;display:flex}.ntm-manage-members__header>*+*{margin-inline-start:.5rem}.ntm-product-roles-table th{color:rgb(var(--neeto-ui-gray-700));font-size:var(--neeto-ui-text-xs);font-weight:var(--neeto-ui-font-bold);text-transform:uppercase;vertical-align:middle}.ntm-product-roles-table td,.ntm-product-roles-table th{border:1px solid rgb(var(--neeto-ui-gray-200));padding:.5rem;text-align:start}.ntm-manage-members__app-roles{align-items:center;display:flex;justify-content:space-between;padding:.5rem 0;width:100%}.ntm-manage-members-app-roles__select-wrapper{max-width:250px;width:50%}.ntm-manage-members-effective-app-roles{align-items:center;display:flex;justify-content:space-between;padding:.25rem 0}.ntm-manage-members-effective-app-roles__role-name{max-width:300px;width:67%}.ntm-manage-members__checkbox-align-start.neeto-ui-checkbox__wrapper .neeto-ui-checkbox__container{align-items:flex-start}.ntm-manage-members__checkbox-align-start.neeto-ui-checkbox__wrapper .neeto-ui-checkbox[type=checkbox]{margin-top:.25rem}.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))}.ntm-members-table__wrapper{display:flex;gap:.75rem;justify-content:space-between;width:100%}.ntm-members-table__column{align-items:center;display:flex;gap:.5rem}.ntm-members-form__header{margin-bottom:.5rem}.ntm-members-form__body{padding-bottom:1rem;width:100%}.ntm-members-form__body>*+*{margin-top:1rem}.ntm-members-form__footer{display:flex;gap:.5rem}\n/*# sourceMappingURL=data:application/json;base64,  */";
injectCss.n(css,{});

var FIXED_COLUMNS = ["name", "actions"];
var MANAGE_ROLES_BUTTON_LABEL = i18next.t("neetoTeamMembers.labels.manageRole", constants.PLURAL);

function ownKeys$4(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$4(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$4(Object(t), true).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var Header$2 = function Header(_ref) {
  var isCreatePermissionGranted = _ref.isCreatePermissionGranted,
    otherActionBlock = _ref.otherActionBlock,
    _ref$onClick = _ref.onClick,
    onClick = _ref$onClick === void 0 ? neetoCist.noop : _ref$onClick,
    rolesButtonProps = _ref.rolesButtonProps;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var isRolesButtonVisible = !!rolesButtonProps;
  var isOtherActionBlockVisible = !!otherActionBlock;
  return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
    children: [isOtherActionBlockVisible && otherActionBlock(), isRolesButtonVisible ? /*#__PURE__*/jsxRuntime.jsx(Button__default.default, _objectSpread$4({
      "data-testid": "ntm-manage-roles-button",
      label: MANAGE_ROLES_BUTTON_LABEL,
      style: "secondary"
    }, rolesButtonProps)) : null, /*#__PURE__*/jsxRuntime.jsx(Tooltip__default.default, {
      content: t("neetoTeamMembers.tooltips.noPermissionToAddMember"),
      disabled: isCreatePermissionGranted,
      position: "bottom",
      children: /*#__PURE__*/jsxRuntime.jsx("span", {
        children: /*#__PURE__*/jsxRuntime.jsx(Button__default.default, {
          onClick: onClick,
          "data-testid": "ntm-add-member-button",
          disabled: !isCreatePermissionGranted,
          label: t("neetoTeamMembers.common.addNew_", {
            what: initializers.taxonomies.member.singular
          })
        })
      })
    })]
  });
};
var HeaderActionBlock = /*#__PURE__*/React.memo(Header$2);

var filterBySearchTerm = function filterBySearchTerm(searchTerm, roles) {
  return ramda.filter(function (_ref) {
    var name = _ref.name;
    return ramda.includes(ramda.trim(ramda.toLower(searchTerm)), ramda.trim(ramda.toLower(name)));
  }, roles);
};
var getDeactivatedButtonVisible = function getDeactivatedButtonVisible(selectedRows, config) {
  var _config$hiddenBulkAct;
  return selectedRows.active.some(function (active) {
    return active === true;
  }) && !(config !== null && config !== void 0 && (_config$hiddenBulkAct = config.hiddenBulkActions) !== null && _config$hiddenBulkAct !== void 0 && _config$hiddenBulkAct.includes("remove"));
};

var Menu$1 = Dropdown__default.default.Menu,
  MenuItem$1 = Dropdown__default.default.MenuItem;
var RolesDropdown = function RolesDropdown(_ref) {
  var _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    hasUpdatePermission = _ref.hasUpdatePermission,
    _ref$isSearchable = _ref.isSearchable,
    isSearchable = _ref$isSearchable === void 0 ? false : _ref$isSearchable,
    _ref$roles = _ref.roles,
    roles = _ref$roles === void 0 ? [] : _ref$roles,
    _ref$selectedMembersC = _ref.selectedMembersCount,
    selectedMembersCount = _ref$selectedMembersC === void 0 ? 0 : _ref$selectedMembersC,
    setAlertType = _ref.setAlertType,
    setBulkUpdateRole = _ref.setBulkUpdateRole;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useState = React.useState(false),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    isDropdownOpen = _useState2[0],
    setIsDropdownOpen = _useState2[1];
  var _useState3 = React.useState(""),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    searchTerm = _useState4[0],
    setSearchTerm = _useState4[1];
  var filteredRoles = filterBySearchTerm(searchTerm, roles);
  var isUpdatingAllowed = hasUpdatePermission && !disabled;
  var handleSearch = function handleSearch(_ref2) {
    var value = _ref2.target.value;
    return setSearchTerm(value);
  };
  var handleSelectRole = function handleSelectRole(role) {
    setBulkUpdateRole(role);
    setAlertType("role");
    setIsDropdownOpen(false);
  };
  var handleOnClose = function handleOnClose() {
    setSearchTerm("");
    setIsDropdownOpen(false);
  };
  var handleClick = function handleClick(event) {
    event.stopPropagation();
    setIsDropdownOpen(!isDropdownOpen);
  };
  return /*#__PURE__*/jsxRuntime.jsx(Tooltip__default.default, {
    disabled: isUpdatingAllowed,
    position: "top",
    content: t("neetoTeamMembers.tooltips.activateUserToEdit", {
      count: selectedMembersCount
    }),
    children: /*#__PURE__*/jsxRuntime.jsx("span", {
      children: /*#__PURE__*/jsxRuntime.jsx(Dropdown__default.default, {
        buttonStyle: "secondary",
        closeOnSelect: false,
        "data-testid": "ntm-members-roles-update-dropdown-button",
        disabled: !isUpdatingAllowed,
        isOpen: isUpdatingAllowed && isDropdownOpen,
        position: "auto-end",
        customTarget: /*#__PURE__*/jsxRuntime.jsx(MenuItem$1.Button, {
          "data-testid": "take-action-dropdown-change-role-button",
          disabled: !isUpdatingAllowed,
          suffix: /*#__PURE__*/jsxRuntime.jsx(Right__default.default, {
            size: 16
          }),
          children: t("neetoTeamMembers.buttons.changeRole")
        }),
        onClick: handleClick,
        onClose: handleOnClose,
        children: /*#__PURE__*/jsxRuntime.jsxs(Menu$1, {
          children: [isSearchable && /*#__PURE__*/jsxRuntime.jsx("div", {
            className: "neeto-ui-px-3 neeto-ui-py-2",
            onClick: function onClick(event) {
              event.stopPropagation();
            },
            children: /*#__PURE__*/jsxRuntime.jsx(Input__default.default, {
              "data-testid": "ntm-members-roles-search-input",
              prefix: /*#__PURE__*/jsxRuntime.jsx(NeetoUISearchIcon__default.default, {}),
              type: "search",
              value: searchTerm,
              placeholder: t("neetoTeamMembers.placeholders.searchRole", constants.PLURAL),
              onChange: handleSearch
            })
          }), neetoCist.isNotEmpty(filteredRoles) ? filteredRoles.map(function (_ref3) {
            var id = _ref3.id,
              name = _ref3.name;
            return /*#__PURE__*/jsxRuntime.jsx(MenuItem$1.Button, {
              "data-testid": "change-role-".concat(neetoCist.hyphenate(name), "-button"),
              onClick: function onClick() {
                return handleSelectRole(name);
              },
              children: name
            }, id);
          }) : /*#__PURE__*/jsxRuntime.jsx("div", {
            className: "neeto-ui-flex neeto-ui-justify-center neeto-ui-p-1",
            children: /*#__PURE__*/jsxRuntime.jsx(Typography__default.default, {
              className: "neeto-ui-text-gray-700",
              style: "body2",
              children: t("neetoTeamMembers.helpers.noRolesFound")
            })
          })]
        })
      })
    })
  });
};

function ownKeys$3(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$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), true).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var Menu = Dropdown__default.default.Menu,
  MenuItem = Dropdown__default.default.MenuItem;
var Left = function Left(_ref) {
  var _ref2, _selectedRows$keys, _selectedRows$active, _config$hiddenBulkAct, _config$otherBulkActi;
  var config = _ref.config,
    filteredCount = _ref.filteredCount,
    resetToFirstPage = _ref.resetToFirstPage,
    roles = _ref.roles,
    selectedRows = _ref.selectedRows,
    setSelectedRows = _ref.setSelectedRows,
    selectedRowsCount = _ref.selectedRowsCount,
    bulkParams = _ref.bulkParams;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var isUpdatePermissionGranted = config.permissions.update;
  var _useState = React.useState(""),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    alertType = _useState2[0],
    setAlertType = _useState2[1];
  var _useState3 = React.useState(""),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    bulkUpdateRole = _useState4[0],
    setBulkUpdateRole = _useState4[1];
  var hasSelectedRows = neetoCist.isNotEmpty(selectedRows === null || selectedRows === void 0 ? void 0 : selectedRows.keys);
  var selectedMembersCountValues = {
    count: (_ref2 = selectedRowsCount || (selectedRows === null || selectedRows === void 0 || (_selectedRows$keys = selectedRows.keys) === null || _selectedRows$keys === void 0 ? void 0 : _selectedRows$keys.length) || filteredCount) !== null && _ref2 !== void 0 ? _ref2 : 0,
    metaName: hasSelectedRows && (selectedRows === null || selectedRows === void 0 ? void 0 : selectedRows.keys.length) > 1 ? initializers.taxonomies.member.plural : initializers.taxonomies.member.singular,
    totalCount: filteredCount !== null && filteredCount !== void 0 ? filteredCount : 0
  };
  var hasDeactivateMembers = selectedRows === null || selectedRows === void 0 || (_selectedRows$active = selectedRows.active) === null || _selectedRows$active === void 0 ? void 0 : _selectedRows$active.some(function (active) {
    return !active;
  });
  var _useBulkUpdateMembers = useTeamsApi.useBulkUpdateMembers({
      onSuccess: function onSuccess() {
        var _config$bulkUpdateMem;
        setSelectedRows(utils.DEFAULT_SELECTED_ROWS);
        resetToFirstPage();
        config === null || config === void 0 || (_config$bulkUpdateMem = config.bulkUpdateMembers) === null || _config$bulkUpdateMem === void 0 || (_config$bulkUpdateMem = _config$bulkUpdateMem.onSuccess) === null || _config$bulkUpdateMem === void 0 || _config$bulkUpdateMem.callback();
      }
    }),
    bulkUpdateMember = _useBulkUpdateMembers.mutate;
  var handleDeactivateMembers = function handleDeactivateMembers() {
    bulkUpdateMember({
      users: {
        active: false,
        emails: selectedRows === null || selectedRows === void 0 ? void 0 : selectedRows.emails
      },
      filterParams: bulkParams
    });
  };
  var resetSelectedRows = function resetSelectedRows() {
    return setSelectedRows(utils.DEFAULT_SELECTED_ROWS);
  };
  var handleRoleChange = function handleRoleChange(role) {
    bulkUpdateMember({
      users: {
        active: true,
        emails: selectedRows === null || selectedRows === void 0 ? void 0 : selectedRows.emails,
        organization_role: role
      },
      filterParams: bulkParams
    });
  };
  var alertTypes = [{
    message: "neetoTeamMembers.alerts.messages.removeMember",
    onSubmit: handleDeactivateMembers,
    title: t("neetoTeamMembers.common.remove_", {
      what: selectedMembersCountValues === null || selectedMembersCountValues === void 0 ? void 0 : selectedMembersCountValues.metaName
    }),
    type: "remove"
  }, {
    message: "neetoTeamMembers.alerts.messages.changeRole",
    onSubmit: handleRoleChange,
    title: t("neetoTeamMembers.common.changeRole"),
    type: "role"
  }];
  var selectedAlert = neetoCist.findBy({
    type: alertType
  }, alertTypes);
  var handleAlertClose = function handleAlertClose() {
    selectedAlert.onSubmit(bulkUpdateRole);
    setAlertType("");
  };
  var getButtonLabel = function getButtonLabel(type) {
    if (type === "role") {
      return t("neetoTeamMembers.buttons.changeRole");
    }
    return t("neetoTeamMembers.buttons.remove");
  };
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "neeto-ui-flex neeto-ui-items-center neeto-ui-gap-4",
    children: [/*#__PURE__*/jsxRuntime.jsx(Typography__default.default, {
      component: "h4",
      "data-testid": "ntm-filtered-members-count",
      style: "h4",
      children: /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
        components: {
          span: /*#__PURE__*/jsxRuntime.jsx("span", {
            className: "neeto-ui-text-gray-600"
          })
        },
        values: selectedMembersCountValues,
        i18nKey: hasSelectedRows ? "neetoTeamMembers.helpers.selectedMembersCount" : "neetoTeamMembers.helpers.metaNameWithCount"
      })
    }), hasSelectedRows && /*#__PURE__*/jsxRuntime.jsx(Tooltip__default.default, {
      content: t("neetoTeamMembers.tooltips.noPermissionToEditMembers"),
      disabled: isUpdatePermissionGranted,
      position: "top",
      children: /*#__PURE__*/jsxRuntime.jsx("span", {
        children: /*#__PURE__*/jsxRuntime.jsx(Dropdown__default.default, {
          buttonStyle: "secondary",
          "data-testid": "ntm-members-take-action-dropdown-button",
          disabled: !isUpdatePermissionGranted,
          label: t("neetoTeamMembers.common.takeAction"),
          children: /*#__PURE__*/jsxRuntime.jsxs(Menu, {
            children: [!(config !== null && config !== void 0 && (_config$hiddenBulkAct = config.hiddenBulkActions) !== null && _config$hiddenBulkAct !== void 0 && _config$hiddenBulkAct.includes("role")) && /*#__PURE__*/jsxRuntime.jsx(RolesDropdown, {
              roles: roles,
              setAlertType: setAlertType,
              setBulkUpdateRole: setBulkUpdateRole,
              disabled: hasDeactivateMembers,
              hasUpdatePermission: isUpdatePermissionGranted,
              selectedMembersCount: selectedMembersCountValues === null || selectedMembersCountValues === void 0 ? void 0 : selectedMembersCountValues.count
            }), config === null || config === void 0 || (_config$otherBulkActi = config.otherBulkActions) === null || _config$otherBulkActi === void 0 ? void 0 : _config$otherBulkActi.call(config, resetSelectedRows, selectedRows), getDeactivatedButtonVisible(selectedRows, config) && /*#__PURE__*/jsxRuntime.jsx(MenuItem.Button, {
              "data-testid": "ntm-deactivate-members-button",
              disabled: !isUpdatePermissionGranted,
              onClick: function onClick() {
                return setAlertType("remove");
              },
              children: t("neetoTeamMembers.common.remove")
            })]
          })
        })
      })
    }), /*#__PURE__*/jsxRuntime.jsx(Alert__default.default, {
      isOpen: selectedAlert,
      submitButtonLabel: getButtonLabel(selectedAlert === null || selectedAlert === void 0 ? void 0 : selectedAlert.type),
      title: selectedAlert === null || selectedAlert === void 0 ? void 0 : selectedAlert.title,
      message: /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
        i18nKey: selectedAlert === null || selectedAlert === void 0 ? void 0 : selectedAlert.message,
        values: _objectSpread$3(_objectSpread$3({}, selectedMembersCountValues), {}, {
          person: selectedRows.displayNames[0],
          role: bulkUpdateRole
        })
      }),
      onClose: function onClose() {
        return setAlertType("");
      },
      onSubmit: handleAlertClose
    })]
  });
};
var Right = reactUtils.withT(function (_ref3) {
  var t = _ref3.t,
    columns = _ref3.columns,
    filterColumns = _ref3.filterColumns,
    handleNeetoFilterChange = _ref3.handleNeetoFilterChange,
    isFiltersPaneOpen = _ref3.isFiltersPaneOpen,
    searchKeywordProps = _ref3.searchKeywordProps,
    setIsDownloadPaneOpen = _ref3.setIsDownloadPaneOpen,
    setIsFiltersPaneOpen = _ref3.setIsFiltersPaneOpen;
  return /*#__PURE__*/jsxRuntime.jsx(SubHeader__default.default.RightBlock, {
    columnsButtonProps: {
      columnData: columns,
      fixedColumns: FIXED_COLUMNS,
      tableKey: constants$1.TABLE_KEYS.TEAM_MEMBERS_TABLE,
      noColumnMessage: t("neetoTeamMembers.columns.noColumnsFound"),
      searchProps: {
        placeholder: t("neetoTeamMembers.columns.search")
      }
    },
    downloadButtonProps: {
      isVisible: true,
      tooltipProps: {
        content: t("neetoTeamMembers.buttons.export")
      },
      onClick: function onClick() {
        return setIsDownloadPaneOpen(true);
      }
    },
    filterProps: {
      columns: filterColumns,
      isOpen: isFiltersPaneOpen,
      setIsOpen: setIsFiltersPaneOpen,
      onChange: handleNeetoFilterChange,
      keyword: searchKeywordProps
    }
  });
});
var SubHeader = {
  Left: Left,
  Right: Right
};

var EXPORT_TYPES = {
  PDF: "pdf",
  CSV: "csv",
  EXCEL: "xlsx"
};
var DEFAULT_EXPORT_OPTIONS = {
  exportType: EXPORT_TYPES.EXCEL
};
var EXPORT_OPTIONS = [{
  type: EXPORT_TYPES.EXCEL,
  individualExportLabel: i18next.t("neetoTeamMembers.labels.exports.xlsx"),
  bulkExportLabel: i18next.t("neetoTeamMembers.labels.exportAs", {
    format: i18next.t("neetoTeamMembers.labels.exports.xlsx")
  }),
  dataTestid: "download-as-excel-radio-item"
}, {
  type: EXPORT_TYPES.CSV,
  individualExportLabel: i18next.t("neetoTeamMembers.labels.exports.csv"),
  bulkExportLabel: i18next.t("neetoTeamMembers.labels.exportAs", {
    format: i18next.t("neetoTeamMembers.labels.exports.csv")
  }),
  dataTestid: "download-as-csv-radio-item"
}, {
  type: EXPORT_TYPES.PDF,
  individualExportLabel: i18next.t("neetoTeamMembers.labels.exports.pdf"),
  bulkExportLabel: i18next.t("neetoTeamMembers.labels.exportAs", {
    format: i18next.t("neetoTeamMembers.labels.exports.pdf")
  }),
  dataTestid: "download-as-pdf-radio-item"
}];

function ownKeys$2(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$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var ExportPane = function ExportPane(_ref) {
  var isOpen = _ref.isOpen,
    onClose = _ref.onClose,
    appliedFilters = _ref.appliedFilters,
    hasBulkSelectedAllRows = _ref.hasBulkSelectedAllRows,
    selectedMemberIds = _ref.selectedMemberIds,
    selectedRowsCount = _ref.selectedRowsCount;
  var _useState = React.useState(DEFAULT_EXPORT_OPTIONS),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    exportOptions = _useState2[0],
    setExportOptions = _useState2[1];
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var setExportOption = function setExportOption(exportOptions) {
    return setExportOptions(ramda.mergeLeft(exportOptions));
  };
  var exportType = exportOptions.exportType;
  var getParams = function getParams() {
    return _objectSpread$2(_objectSpread$2({}, exportOptions), {}, {
      filters: appliedFilters || undefined,
      considerAllMembers: hasBulkSelectedAllRows,
      memberIds: hasBulkSelectedAllRows ? undefined : selectedMemberIds
    });
  };
  var _useExportMembers = useTeamsApi.useExportMembers({
      onSuccess: function onSuccess() {
        var _globalProps$user;
        onClose();
        setExportOptions(DEFAULT_EXPORT_OPTIONS);
        Toastr__default.default.success(/*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
          i18nKey: "toastr.success.exportMembers",
          values: {
            email: (_globalProps$user = initializers.globalProps.user) === null || _globalProps$user === void 0 ? void 0 : _globalProps$user.email
          }
        }));
        utils$1.captureAnalyticsEvent(constants$1.EVENTS.TEAM_MEMBERS_DOWNLOADED, _objectSpread$2({}, exportOptions));
      },
      onError: function onError(error) {
        return Toastr__default.default.error(error.message);
      }
    }),
    exportMembers = _useExportMembers.mutate;
  var description = neetoCist.isNotEmpty(selectedMemberIds) || hasBulkSelectedAllRows ? t("neetoTeamMembers.exportPane.description.selectedMembers", {
    count: selectedRowsCount
  }) : t("neetoTeamMembers.exportPane.description.allMembers");
  return /*#__PURE__*/jsxRuntime.jsxs(Pane__default.default, {
    isOpen: isOpen,
    onClose: onClose,
    children: [/*#__PURE__*/jsxRuntime.jsx(Pane__default.default.Header, {
      children: /*#__PURE__*/jsxRuntime.jsx(Typography__default.default, {
        "data-testid": "export-member-heading",
        style: "h2",
        children: t("neetoTeamMembers.exportPane.title")
      })
    }), /*#__PURE__*/jsxRuntime.jsx(Pane__default.default.Body, {
      children: /*#__PURE__*/jsxRuntime.jsx(Radio__default.default, {
        stacked: true,
        className: "grow-0 space-y-4",
        label: description,
        children: EXPORT_OPTIONS.map(function (_ref2) {
          var type = _ref2.type,
            bulkExportLabel = _ref2.bulkExportLabel,
            dataTestid = _ref2.dataTestid;
          return /*#__PURE__*/jsxRuntime.jsx(Radio__default.default.Item, {
            checked: exportType === type,
            "data-testid": dataTestid,
            label: bulkExportLabel,
            onChange: function onChange() {
              return setExportOption({
                exportType: type
              });
            }
          }, type);
        })
      })
    }), /*#__PURE__*/jsxRuntime.jsxs(Pane__default.default.Footer, {
      className: "gap-x-2",
      children: [/*#__PURE__*/jsxRuntime.jsx(Button__default.default, {
        "data-testid": "export-submit-button",
        label: t("neetoTeamMembers.buttons.export"),
        onClick: function onClick() {
          return exportMembers({
            "export": getParams()
          });
        }
      }), /*#__PURE__*/jsxRuntime.jsx(Button__default.default, {
        className: "me-2",
        "data-testid": "export-cancel-button",
        label: t("neetoTeamMembers.buttons.cancel"),
        style: "text",
        onClick: onClose
      })]
    })]
  });
};

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 Header = function Header(_ref) {
  var _config$header, _config$header2;
  var config = _ref.config,
    setIsOpen = _ref.setIsOpen,
    searchProps = _ref.searchProps;
  return /*#__PURE__*/jsxRuntime.jsx(NeetoHeader__default.default, _objectSpread$1({
    searchProps: searchProps,
    title: initializers.taxonomies.member.plural,
    actionBlock: /*#__PURE__*/jsxRuntime.jsx(HeaderActionBlock, {
      isCreatePermissionGranted: config.permissions.create,
      otherActionBlock: (_config$header = config.header) === null || _config$header === void 0 ? void 0 : _config$header.otherActionBlock,
      rolesButtonProps: config.rolesButtonProps,
      onClick: function onClick() {
        return setIsOpen(ramda.assoc("manageMember", true));
      }
    })
  }, config === null || config === void 0 || (_config$header2 = config.header) === null || _config$header2 === void 0 ? void 0 : _config$header2.otherProps));
};
var Header$1 = /*#__PURE__*/React.memo(Header);

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 TeamMembers = function TeamMembers(_ref) {
  var _config$fetchApiRespo, _config$table, _config$table$onDropd, _config$table2, _filters$pageSize3, _filters$pageSize4;
  var config = _ref.config;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var history = reactRouterDom.useHistory();
  var _useBreakpoints = reactUtils.useBreakpoints(),
    isSize = _useBreakpoints.isSize;
  var queryParams = reactUtils.useQueryParams();
  var isViewPermissionGranted = config.permissions.view;
  var isCreatePermissionGranted = config.permissions.create;
  var _useState = React.useState(false),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    isFiltersPaneOpen = _useState2[0],
    setIsFiltersPaneOpen = _useState2[1];
  var _useState3 = React.useState(false),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    isDownloadPaneOpen = _useState4[0],
    setIsDownloadPaneOpen = _useState4[1];
  var _useState5 = React.useState(false),
    _useState6 = _slicedToArray__default.default(_useState5, 2),
    hasBulkSelectedAllRows = _useState6[0],
    setHasBulkSelectedAllRows = _useState6[1];
  React.useEffect(function () {
    handleMemberFilterChange();
  }, []);
  var _useFilters = useTeams.useFilters({
      config: config
    }),
    filters = _useFilters.filters,
    setFilters = _useFilters.setFilters,
    filterColumns = _useFilters.filterColumns,
    searchProps = _useFilters.searchProps,
    searchKeywordProps = _useFilters.searchKeywordProps;
  var _useFetchMembers = useTeamsApi.useFetchMembers(_objectSpread({}, filters), {
      enabled: isViewPermissionGranted
    }),
    team = _useFetchMembers.data,
    isMembersLoading = _useFetchMembers.isLoading,
    isMembersFetching = _useFetchMembers.isFetching;
  var bulkParams = {
    neetoFilters: filters["neetoFilters"],
    considerAllTeamMembers: hasBulkSelectedAllRows
  };
  var _useFetchRoles = useRolesApi.useFetchRoles({
      select: function select(response) {
        var _response$organizatio;
        return ramda.reverse((_response$organizatio = response === null || response === void 0 ? void 0 : response.organizationRoles) !== null && _response$organizatio !== void 0 ? _response$organizatio : []);
      },
      enabled: isViewPermissionGranted
    }),
    roles = _useFetchRoles.data,
    isRolesLoading = _useFetchRoles.isLoading;
  var _useUpdateMember = useTeamsApi.useUpdateMember({
      onSuccess: function onSuccess() {
        var _filters$pageSize, _config$updateMember;
        handleAlertClose();
        utils.handlePageChange(setFilters, history)(constants.DEFAULT_PAGE_INDEX, (_filters$pageSize = filters.pageSize) !== null && _filters$pageSize !== void 0 ? _filters$pageSize : constants.DEFAULT_PAGE_SIZE);
        config === null || config === void 0 || (_config$updateMember = config.updateMember) === null || _config$updateMember === void 0 || (_config$updateMember = _config$updateMember.onSuccess) === null || _config$updateMember === void 0 || _config$updateMember.callback();
      }
    }),
    updateMember = _useUpdateMember.mutate,
    isUpdatingMember = _useUpdateMember.isPending;
  var filteredRoles = utils.getFilteredRoles(roles, config);
  var _useTeams = useTeams.useTeams({
      config: config,
      filters: filters,
      setFilters: setFilters,
      updateMember: updateMember
    }),
    handleAlertClose = _useTeams.handleAlertClose,
    handleMemberFilterChange = _useTeams.handleMemberFilterChange,
    handlePaneClose = _useTeams.handlePaneClose,
    handleRowSelect = _useTeams.handleRowSelect,
    handleTableChange = _useTeams.handleTableChange,
    handleRemoveMember = _useTeams.handleRemoveMember,
    handleUpdateRole = _useTeams.handleUpdateRole,
    handleUpdateStatus = _useTeams.handleUpdateStatus,
    isOpen = _useTeams.isOpen,
    selectedMember = _useTeams.selectedMember,
    selectedRows = _useTeams.selectedRows,
    setIsOpen = _useTeams.setIsOpen,
    setSelectedRows = _useTeams.setSelectedRows;
  var selectedRowsCount = hasBulkSelectedAllRows ? team === null || team === void 0 ? void 0 : team.membersCount : selectedRows.keys.length;
  config === null || config === void 0 || (_config$fetchApiRespo = config.fetchApiResponse) === null || _config$fetchApiRespo === void 0 || _config$fetchApiRespo.call(config, {
    team: team
  });
  var hasMembers = (team === null || team === void 0 ? void 0 : team.activeUsersCount) > 0;
  var updateMemberAlertProps = {
    member: selectedMember,
    config: config
  };
  config === null || config === void 0 || (_config$table = config.table) === null || _config$table === void 0 || (_config$table$onDropd = _config$table.onDropdownClick) === null || _config$table$onDropd === void 0 || _config$table$onDropd.call(_config$table, {
    handleUpdateRole: handleUpdateRole,
    handleUpdateStatus: handleUpdateStatus
  });
  var columns = React.useMemo(function () {
    return utils.getColumnData({
      config: config,
      handleUpdateRole: handleUpdateRole,
      handleUpdateStatus: handleUpdateStatus,
      isSize: isSize
    });
  }, [(_config$table2 = config.table) === null || _config$table2 === void 0 ? void 0 : _config$table2.dropdownProps] // eslint-disable-line react-hooks/exhaustive-deps
  );
  var _useTableConfiguratio = Columns.useTableConfigurations(constants$1.TABLE_KEYS.TEAM_MEMBERS_TABLE, columns),
    isTableConfigurationLoading = _useTableConfiguratio.isTableConfigurationLoading,
    customizedColumns = _useTableConfiguratio.customizedColumns,
    hideColumn = _useTableConfiguratio.hideColumn;
  var handleNeetoFilterChange = function handleNeetoFilterChange(filters) {
    setFilters(ramda.mergeLeft({
      neetoFilters: filters,
      page: constants.DEFAULT_PAGE_INDEX
    }));
    setSelectedRows(utils.DEFAULT_SELECTED_ROWS);
    history.push(utils$1.buildUrl(window.location.pathname, ramda.mergeLeft({
      page: constants.DEFAULT_PAGE_INDEX
    }, queryParams)));
  };
  var _generateNoDataConten = utils.generateNoDataContent({
      buttonProps: {
        onClick: function onClick() {
          return setIsOpen(ramda.assoc("manageMember", true));
        },
        disabled: !isCreatePermissionGranted
      }
    }),
    noDataTitle = _generateNoDataConten.noDataTitle,
    noDataButtonProps = _generateNoDataConten.noDataButtonProps;
  if (isRolesLoading || isMembersLoading) {
    return /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "flex h-full min-h-screen w-full items-center justify-center",
      children: /*#__PURE__*/jsxRuntime.jsx(Spinner__default.default, {})
    });
  }
  return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
    children: [/*#__PURE__*/jsxRuntime.jsxs(Container__default.default, {
      className: "ntm-members",
      children: [/*#__PURE__*/jsxRuntime.jsx(Header$1, {
        config: config,
        setIsOpen: setIsOpen,
        searchProps: hasMembers ? searchProps : null
      }), /*#__PURE__*/jsxRuntime.jsx(SubHeader__default.default, {
        className: "mb-4",
        leftActionBlock: hasMembers && /*#__PURE__*/jsxRuntime.jsx(SubHeader.Left, {
          bulkParams: bulkParams,
          config: config,
          selectedRows: selectedRows,
          selectedRowsCount: selectedRowsCount,
          setSelectedRows: setSelectedRows,
          filteredCount: team === null || team === void 0 ? void 0 : team.membersCount,
          roles: filteredRoles,
          resetToFirstPage: function resetToFirstPage() {
            var _filters$pageSize2;
            return utils.handlePageChange(setFilters, history)(constants.DEFAULT_PAGE_INDEX, (_filters$pageSize2 = filters.pageSize) !== null && _filters$pageSize2 !== void 0 ? _filters$pageSize2 : constants.DEFAULT_PAGE_SIZE);
          }
        }),
        rightActionBlock: hasMembers && /*#__PURE__*/jsxRuntime.jsx(SubHeader.Right, {
          columns: columns,
          filterColumns: filterColumns,
          handleNeetoFilterChange: handleNeetoFilterChange,
          isFiltersPaneOpen: isFiltersPaneOpen,
          searchKeywordProps: searchKeywordProps,
          setIsDownloadPaneOpen: setIsDownloadPaneOpen,
          setIsFiltersPaneOpen: setIsFiltersPaneOpen
        })
      }), /*#__PURE__*/jsxRuntime.jsx(FiltersBar__default.default, {
        className: "mb-4",
        columns: filterColumns,
        keyword: searchKeywordProps,
        setIsPaneOpen: setIsFiltersPaneOpen,
        onChange: handleNeetoFilterChange
      }), /*#__PURE__*/jsxRuntime.jsx(ExportPane, {
        hasBulkSelectedAllRows: hasBulkSelectedAllRows,
        selectedRowsCount: selectedRowsCount,
        appliedFilters: filters,
        isOpen: isDownloadPaneOpen,
        selectedMemberIds: selectedRows.keys,
        onClose: function onClose() {
          return setIsDownloadPaneOpen(false);
        }
      }), /*#__PURE__*/jsxRuntime.jsx(TableWrapper__default.default, {
        hasPagination: (team === null || team === void 0 ? void 0 : team.membersCount) > ((_filters$pageSize3 = filters.pageSize) !== null && _filters$pageSize3 !== void 0 ? _filters$pageSize3 : constants.DEFAULT_PAGE_SIZE),
        children: (team === null || team === void 0 ? void 0 : team.membersCount) !== 0 ? /*#__PURE__*/jsxRuntime.jsx(Table__default.default, {
          fixedHeight: true,
          allowRowClick: false,
          columnData: customizedColumns,
          currentPageNumber: parseInt(filters.page, utils.DEFAULT_RADIX),
          "data-testid": "ntm-members-table",
          handlePageChange: utils.handlePageChange(setFilters, history),
          loading: isMembersFetching || isTableConfigurationLoading,
          rowData: team === null || team === void 0 ? void 0 : team.members,
          selectedRowKeys: selectedRows.keys,
          tableLayout: "fixed",
          totalCount: team === null || team === void 0 ? void 0 : team.membersCount,
          bulkSelectAllRowsProps: {
            selectAllRowMessage: t("neetoTeamMembers.helpers.selectedMembers", {
              count: selectedRowsCount
            }),
            selectAllRowButtonLabel: t("neetoTeamMembers.helpers.selectAll", {
              count: team === null || team === void 0 ? void 0 : team.membersCount
            }),
            setBulkSelectedAllRows: setHasBulkSelectedAllRows
          },
          paginationProps: utils.renderPaginationProps((_filters$pageSize4 = filters.pageSize) !== null && _filters$pageSize4 !== void 0 ? _filters$pageSize4 : constants.DEFAULT_PAGE_SIZE),
          rowSelection: {
            getCheckboxProps: function getCheckboxProps() {
              return {
                "data-testid": "row-selection-checkbox"
              };
            }
          },
          onChange: handleTableChange,
          onColumnHide: function onColumnHide(_ref2) {
            var key = _ref2.key;
            return hideColumn(key);
          },
          onRowSelect: handleRowSelect
        }) : /*#__PURE__*/jsxRuntime.jsx("div", {
          className: "flex h-full w-full items-center justify-center",
          children: /*#__PURE__*/jsxRuntime.jsx(NoData__default.default, {
            primaryButtonProps: noDataButtonProps,
            title: noDataTitle
          })
        })
      })]
    }), /*#__PURE__*/jsxRuntime.jsx(ManageMember, {
      config: config,
      selectedMember: selectedMember,
      componentConfig: {
        isOpen: isOpen.manageMember
      },
      roles: filteredRoles,
      onComplete: handlePaneClose
    }), /*#__PURE__*/jsxRuntime.jsx(Alert__default.default, {
      cancelButtonLabel: t("neetoTeamMembers.buttons.cancel"),
      isOpen: isOpen.alert,
      isSubmitting: isUpdatingMember,
      message: utils.renderUpdateAlert("message", updateMemberAlertProps),
      submitButtonLabel: t("neetoTeamMembers.buttons.remove"),
      title: utils.renderUpdateAlert("title", updateMemberAlertProps),
      onClose: handleAlertClose,
      onSubmit: handleRemoveMember
    })]
  });
};
var index = reactUtils.withTitle(withReactQuery.withReactQuery(TeamMembers), initializers.taxonomies.member.plural);

module.exports = index;
//# sourceMappingURL=TeamMembers.js.map
