'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var React = require('react');
var neetoAtoms = require('@bigbinary/neeto-atoms');
var lucideReact = require('lucide-react');
var constants = require('@bigbinary/neeto-commons-frontend/v2/constants');
var initializers = require('@bigbinary/neeto-commons-frontend/v2/initializers');
var reactUtils = require('@bigbinary/neeto-commons-frontend/v2/react-utils');
var utils = require('@bigbinary/neeto-commons-frontend/v2/utils');
var FiltersBar = require('@bigbinary/neeto-filters-frontend/v2/Bar');
var Columns = require('@bigbinary/neeto-molecules/v2/Columns');
var Container = require('@bigbinary/neeto-molecules/v2/Container');
var SubHeader$1 = require('@bigbinary/neeto-molecules/v2/SubHeader');
var ramda = require('ramda');
var reactI18next = require('react-i18next');
var reactRouterDom = require('react-router-dom');
var useRolesApi = require('../../useRolesApi-DuL4eCuF.js');
var useTeamsApi = require('../../useTeamsApi-ClWGPxNW.js');
var useTeams = require('../../useTeams-C9N2TJY-.js');
var constants$1 = require('../constants.js');
var neetoCist = require('@bigbinary/neeto-cist');
var i18next = require('i18next');
var jsxRuntime = require('react/jsx-runtime');
var v2_ManageMember = require('../../index-D0px8LnB.js');
var sonner = require('sonner');
var NeetoHeader = require('@bigbinary/neeto-molecules/v2/Header');
var withReactQuery = require('../../withReactQuery-DvSkXhEx.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('@tanstack/react-query');
require('@bigbinary/neeto-commons-frontend/react-utils');
require('axios');
require('../../constants-D_H6M1Pm.js');
require('@bigbinary/neeto-commons-frontend/constants');
require('@bigbinary/neeto-commons-frontend/initializers');
require('qs');
require('../../queryClient-4vAFE3bx.js');
require('@babel/runtime/helpers/toConsumableArray');
require('@bigbinary/neeto-filters-frontend/utils');
require('../../utils-CgwJI9pk.js');
require('@bigbinary/neeto-commons-frontend/utils');
require('@bigbinary/neeto-molecules/MoreDropdown');
require('@bigbinary/neetoui/Avatar');
require('@bigbinary/neetoui/Dropdown');
require('@bigbinary/neetoui/Typography');
require('@babel/runtime/helpers/asyncToGenerator');
require('@babel/runtime/regenerator');
require('classnames');
require('@bigbinary/neeto-image-uploader-frontend/hooks');
require('formik');
require('../../RolesRadioGroup-BsARnjvF.js');
require('yup');
require('../../Select-CshPoN2b.js');
require('@bigbinary/neeto-atoms/primitives/Card');
require('@bigbinary/neeto-molecules/v2/CopyToClipboardButton');
require('../../useInviteLinksApi-COVfmZiQ.js');
require('@bigbinary/neeto-atoms/formik');
require('../utils.js');
require('../../_commonjsHelpers-BJu3ubxk.js');
require('@bigbinary/neeto-time-zones');
require('@bigbinary/neeto-molecules/v2/PhoneNumber');
require('../../ProfileImage-BLnx0E90.js');
require('../../inject-css-B6qYtOJe.js');
require('../../useCountriesApi-CjhrbnjK.js');
require('../../ActionBlock-C9Iy0jGZ.js');
require('../../index-BOQKf6as.js');
require('@bigbinary/neeto-atoms/primitives');
require('@bigbinary/neeto-molecules/v2/MoreDropdown');

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 NeetoHeader__default = /*#__PURE__*/_interopDefault(NeetoHeader);

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(neetoAtoms.Button, _objectSpread$4(_objectSpread$4({
      "data-testid": "ntm-manage-roles-button",
      variant: "outline"
    }, rolesButtonProps), {}, {
      children: MANAGE_ROLES_BUTTON_LABEL
    })) : null, /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Tooltip, {
      content: !isCreatePermissionGranted ? t("neetoTeamMembers.tooltips.noPermissionToAddMember") : null,
      children: /*#__PURE__*/jsxRuntime.jsx("span", {
        children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
          onClick: onClick,
          "data-testid": "ntm-add-member-button",
          disabled: !isCreatePermissionGranted,
          children: 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 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(""),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    searchTerm = _useState2[0],
    setSearchTerm = _useState2[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");
  };
  return /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Tooltip, {
    content: !isUpdatingAllowed ? t("neetoTeamMembers.tooltips.activateUserToEdit", {
      count: selectedMembersCount
    }) : null,
    children: /*#__PURE__*/jsxRuntime.jsx("span", {
      children: /*#__PURE__*/jsxRuntime.jsxs(neetoAtoms.DropdownMenu.SubMenu, {
        contentProps: {
          align: "end"
        },
        label: t("neetoTeamMembers.buttons.changeRole"),
        triggerProps: {
          disabled: !isUpdatingAllowed
        },
        children: [isSearchable && /*#__PURE__*/jsxRuntime.jsx("div", {
          className: "px-3 py-2",
          onClick: function onClick(e) {
            return e.stopPropagation();
          },
          children: /*#__PURE__*/jsxRuntime.jsxs("div", {
            className: "relative",
            children: [/*#__PURE__*/jsxRuntime.jsx(lucideReact.Search, {
              className: "absolute left-2 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
            }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Input, {
              className: "ps-8",
              "data-testid": "ntm-members-roles-search-input",
              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(neetoAtoms.DropdownMenu.MenuItem, {
            "data-testid": "change-role-".concat(neetoCist.hyphenate(name), "-button"),
            onClick: function onClick() {
              return handleSelectRole(name);
            },
            children: name
          }, id);
        }) : /*#__PURE__*/jsxRuntime.jsx("div", {
          className: "flex justify-center p-1",
          children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
            color: "muted",
            variant: "body3",
            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 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(v2_ManageMember.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(v2_ManageMember.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: "flex items-center gap-4",
    children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
      "data-testid": "ntm-filtered-members-count",
      variant: "h6",
      children: /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
        components: {
          span: /*#__PURE__*/jsxRuntime.jsx("span", {
            className: "text-muted-foreground"
          })
        },
        values: selectedMembersCountValues,
        i18nKey: hasSelectedRows ? "neetoTeamMembers.helpers.selectedMembersCount" : "neetoTeamMembers.helpers.metaNameWithCount"
      })
    }), hasSelectedRows && /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Tooltip, {
      content: !isUpdatePermissionGranted ? t("neetoTeamMembers.tooltips.noPermissionToEditMembers") : null,
      children: /*#__PURE__*/jsxRuntime.jsx("span", {
        children: /*#__PURE__*/jsxRuntime.jsxs(neetoAtoms.DropdownMenu, {
          disabled: !isUpdatePermissionGranted,
          label: t("neetoTeamMembers.common.takeAction"),
          buttonProps: {
            variant: "outline",
            "data-testid": "ntm-members-take-action-dropdown-button"
          },
          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(neetoAtoms.DropdownMenu.MenuItem, {
            "data-testid": "ntm-deactivate-members-button",
            isDisabled: !isUpdatePermissionGranted,
            onClick: function onClick() {
              return setAlertType("remove");
            },
            children: t("neetoTeamMembers.common.remove")
          })]
        })
      })
    }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Alert, {
      cancelButtonLabel: t("neetoTeamMembers.buttons.cancel"),
      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(options) {
    return setExportOptions(ramda.mergeLeft(options));
  };
  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);
        sonner.toast.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.captureAnalyticsEvent(constants$1.EVENTS.TEAM_MEMBERS_DOWNLOADED, _objectSpread$2({}, exportOptions));
      },
      onError: function onError(error) {
        return sonner.toast.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(neetoAtoms.Sheet, {
    isOpen: isOpen,
    onClose: onClose,
    children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Sheet.Header, {
      children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Sheet.Title, {
        "data-testid": "export-member-heading",
        children: t("neetoTeamMembers.exportPane.title")
      })
    }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Sheet.Body, {
      children: /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "space-y-4",
        children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
          variant: "body3",
          children: description
        }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.RadioGroup, {
          value: exportType,
          onValueChange: function onValueChange(type) {
            return setExportOption({
              exportType: type
            });
          },
          children: EXPORT_OPTIONS.map(function (_ref2) {
            var type = _ref2.type,
              bulkExportLabel = _ref2.bulkExportLabel,
              dataTestid = _ref2.dataTestid;
            return /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.RadioGroup.Item, {
              "data-testid": dataTestid,
              id: type,
              label: bulkExportLabel,
              value: type
            }, type);
          })
        })]
      })
    }), /*#__PURE__*/jsxRuntime.jsxs(neetoAtoms.Sheet.Footer, {
      className: "gap-x-2",
      children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
        "data-testid": "export-submit-button",
        onClick: function onClick() {
          return exportMembers({
            "export": getParams()
          });
        },
        children: t("neetoTeamMembers.buttons.export")
      }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
        "data-testid": "export-cancel-button",
        variant: "ghost",
        onClick: onClose,
        children: t("neetoTeamMembers.buttons.cancel")
      })]
    })]
  });
};

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;
  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();
        v2_ManageMember.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 = v2_ManageMember.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 v2_ManageMember.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(v2_ManageMember.DEFAULT_SELECTED_ROWS);
    history.push(utils.buildUrl(window.location.pathname, ramda.mergeLeft({
      page: constants.DEFAULT_PAGE_INDEX
    }, queryParams)));
  };
  var _generateNoDataConten = v2_ManageMember.generateNoDataContent({
      buttonProps: {
        onClick: function onClick() {
          return setIsOpen(ramda.assoc("manageMember", true));
        },
        disabled: !isCreatePermissionGranted
      }
    }),
    noDataTitle = _generateNoDataConten.noDataTitle,
    noDataDescription = _generateNoDataConten.noDataDescription,
    noDataIcon = _generateNoDataConten.noDataIcon,
    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(neetoAtoms.Spinner, {})
    });
  }
  return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
    children: [/*#__PURE__*/jsxRuntime.jsxs(Container__default.default, {
      className: "pb-10",
      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 v2_ManageMember.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);
        }
      }), !hasMembers ? /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "flex w-full flex-1 items-center justify-center",
        children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Empty, {
          description: noDataDescription,
          icon: noDataIcon,
          primaryButtonProps: noDataButtonProps,
          title: noDataTitle
        })
      }) : (team === null || team === void 0 ? void 0 : team.membersCount) === 0 ? /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "flex w-full flex-1 items-center justify-center",
        children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Empty, {
          icon: lucideReact.Search,
          description: t("neetoTeamMembers.common.memberSearchEmptyDescription"),
          title: t("neetoTeamMembers.common.memberSearchEmptyTitle", {
            what: initializers.taxonomies.member.plural
          })
        })
      }) : /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.DataTable, {
        enableSorting: true,
        fixedHeight: true,
        allowRowClick: false,
        columns: customizedColumns,
        currentPage: parseInt(filters.page, v2_ManageMember.DEFAULT_RADIX),
        data: (team === null || team === void 0 ? void 0 : team.members) || [],
        "data-testid": "ntm-members-table",
        loading: isMembersFetching || isTableConfigurationLoading,
        pageSize: (_filters$pageSize3 = filters.pageSize) !== null && _filters$pageSize3 !== void 0 ? _filters$pageSize3 : constants.DEFAULT_PAGE_SIZE,
        selectedRowKeys: selectedRows.keys,
        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
        },
        onColumnHide: function onColumnHide(columnId) {
          return hideColumn(columnId);
        },
        onPageChange: v2_ManageMember.handlePageChange(setFilters, history),
        onRowSelect: handleRowSelect,
        onSort: handleTableChange
      })]
    }), /*#__PURE__*/jsxRuntime.jsx(v2_ManageMember.ManageMember, {
      config: config,
      selectedMember: selectedMember,
      componentConfig: {
        isOpen: isOpen.manageMember
      },
      roles: filteredRoles,
      onComplete: handlePaneClose
    }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Alert, {
      cancelButtonLabel: t("neetoTeamMembers.buttons.cancel"),
      isOpen: isOpen.alert,
      isSubmitting: isUpdatingMember,
      message: v2_ManageMember.renderUpdateAlert("message", updateMemberAlertProps),
      submitButtonLabel: t("neetoTeamMembers.buttons.remove"),
      title: v2_ManageMember.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
