import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { memo, useState, useEffect, useMemo } from 'react';
import { Button, Tooltip, DropdownMenu, Input, Typography, Alert, Sheet, RadioGroup, Spinner, Empty, DataTable } from '@bigbinary/neeto-atoms';
import { Search } from 'lucide-react';
import { PLURAL, DEFAULT_PAGE_INDEX, DEFAULT_PAGE_SIZE } from '@bigbinary/neeto-commons-frontend/v2/constants';
import { taxonomies, globalProps } from '@bigbinary/neeto-commons-frontend/v2/initializers';
import { withT, withTitle, useBreakpoints, useQueryParams } from '@bigbinary/neeto-commons-frontend/v2/react-utils';
import { captureAnalyticsEvent, buildUrl } from '@bigbinary/neeto-commons-frontend/v2/utils';
import FiltersBar from '@bigbinary/neeto-filters-frontend/v2/Bar';
import { useTableConfigurations } from '@bigbinary/neeto-molecules/v2/Columns';
import Container from '@bigbinary/neeto-molecules/v2/Container';
import SubHeader$1 from '@bigbinary/neeto-molecules/v2/SubHeader';
import { filter, includes, trim, toLower, mergeLeft, assoc, reverse } from 'ramda';
import { useTranslation, Trans } from 'react-i18next';
import { useHistory } from 'react-router-dom';
import { u as useFetchRoles } from '../useRolesApi-93OoRU1s.js';
import { g as useBulkUpdateMembers, h as useExportMembers, u as useFetchMembers, f as useUpdateMember } from '../useTeamsApi-DkgWqw-g.js';
import { u as useFilters, a as useTeams } from '../useTeams-Bw4eltN1.js';
import { TABLE_KEYS, EVENTS } from '../constants.js';
import { noop, isNotEmpty, hyphenate, findBy } from '@bigbinary/neeto-cist';
import { t } from 'i18next';
import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
import { D as DEFAULT_SELECTED_ROWS, h as handlePageChange, g as getFilteredRoles, a as getColumnData, b as generateNoDataContent, c as DEFAULT_RADIX, M as ManageMember, r as renderUpdateAlert } from '../index-CVADXnpl.js';
import { toast } from 'sonner';
import NeetoHeader from '@bigbinary/neeto-molecules/v2/Header';
import { w as withReactQuery } from '../withReactQuery-CSuiy5RK.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import '@tanstack/react-query';
import '@bigbinary/neeto-commons-frontend/react-utils';
import 'axios';
import '../constants-CXdiW8NZ.js';
import '@bigbinary/neeto-commons-frontend/constants';
import '@bigbinary/neeto-commons-frontend/initializers';
import 'qs';
import '../queryClient-Dsu-gu4Y.js';
import '@babel/runtime/helpers/toConsumableArray';
import '@bigbinary/neeto-filters-frontend/utils';
import '../utils-3WlshQ9e.js';
import '@bigbinary/neeto-commons-frontend/utils';
import '@bigbinary/neeto-molecules/MoreDropdown';
import '@bigbinary/neetoui/Avatar';
import '@bigbinary/neetoui/Dropdown';
import '@bigbinary/neetoui/Typography';
import '@babel/runtime/helpers/asyncToGenerator';
import '@babel/runtime/regenerator';
import 'classnames';
import '@bigbinary/neeto-image-uploader-frontend/hooks';
import 'formik';
import '../RolesRadioGroup-CkqMARV8.js';
import 'yup';
import '../Select-DZ56UG-l.js';
import '@bigbinary/neeto-atoms/primitives/Card';
import '@bigbinary/neeto-molecules/v2/CopyToClipboardButton';
import '../useInviteLinksApi-gn-AP0Yx.js';
import '@bigbinary/neeto-atoms/formik';
import '../utils.js';
import '../_commonjsHelpers-BFTU3MAI.js';
import '@bigbinary/neeto-time-zones';
import '@bigbinary/neeto-molecules/v2/PhoneNumber';
import '../ProfileImage-V240yfTY.js';
import '../inject-css-C2dztUxs.js';
import '../useCountriesApi-DK00167T.js';
import '../ActionBlock-jgw1N-As.js';
import '../index-CKQDhbTA.js';
import '@bigbinary/neeto-atoms/primitives';
import '@bigbinary/neeto-molecules/v2/MoreDropdown';

var FIXED_COLUMNS = ["name", "actions"];
var MANAGE_ROLES_BUTTON_LABEL = t("neetoTeamMembers.labels.manageRole", 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(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 ? noop : _ref$onClick,
    rolesButtonProps = _ref.rolesButtonProps;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var isRolesButtonVisible = !!rolesButtonProps;
  var isOtherActionBlockVisible = !!otherActionBlock;
  return /*#__PURE__*/jsxs(Fragment, {
    children: [isOtherActionBlockVisible && otherActionBlock(), isRolesButtonVisible ? /*#__PURE__*/jsx(Button, _objectSpread$4(_objectSpread$4({
      "data-testid": "ntm-manage-roles-button",
      variant: "outline"
    }, rolesButtonProps), {}, {
      children: MANAGE_ROLES_BUTTON_LABEL
    })) : null, /*#__PURE__*/jsx(Tooltip, {
      content: !isCreatePermissionGranted ? t("neetoTeamMembers.tooltips.noPermissionToAddMember") : null,
      children: /*#__PURE__*/jsx("span", {
        children: /*#__PURE__*/jsx(Button, {
          onClick: onClick,
          "data-testid": "ntm-add-member-button",
          disabled: !isCreatePermissionGranted,
          children: t("neetoTeamMembers.common.addNew_", {
            what: taxonomies.member.singular
          })
        })
      })
    })]
  });
};
var HeaderActionBlock = /*#__PURE__*/memo(Header$2);

var filterBySearchTerm = function filterBySearchTerm(searchTerm, roles) {
  return filter(function (_ref) {
    var name = _ref.name;
    return includes(trim(toLower(searchTerm)), trim(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 = useTranslation(),
    t = _useTranslation.t;
  var _useState = useState(""),
    _useState2 = _slicedToArray(_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__*/jsx(Tooltip, {
    content: !isUpdatingAllowed ? t("neetoTeamMembers.tooltips.activateUserToEdit", {
      count: selectedMembersCount
    }) : null,
    children: /*#__PURE__*/jsx("span", {
      children: /*#__PURE__*/jsxs(DropdownMenu.SubMenu, {
        contentProps: {
          align: "end"
        },
        label: t("neetoTeamMembers.buttons.changeRole"),
        triggerProps: {
          disabled: !isUpdatingAllowed
        },
        children: [isSearchable && /*#__PURE__*/jsx("div", {
          className: "px-3 py-2",
          onClick: function onClick(e) {
            return e.stopPropagation();
          },
          children: /*#__PURE__*/jsxs("div", {
            className: "relative",
            children: [/*#__PURE__*/jsx(Search, {
              className: "absolute left-2 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
            }), /*#__PURE__*/jsx(Input, {
              className: "ps-8",
              "data-testid": "ntm-members-roles-search-input",
              type: "search",
              value: searchTerm,
              placeholder: t("neetoTeamMembers.placeholders.searchRole", PLURAL),
              onChange: handleSearch
            })]
          })
        }), isNotEmpty(filteredRoles) ? filteredRoles.map(function (_ref3) {
          var id = _ref3.id,
            name = _ref3.name;
          return /*#__PURE__*/jsx(DropdownMenu.MenuItem, {
            "data-testid": "change-role-".concat(hyphenate(name), "-button"),
            onClick: function onClick() {
              return handleSelectRole(name);
            },
            children: name
          }, id);
        }) : /*#__PURE__*/jsx("div", {
          className: "flex justify-center p-1",
          children: /*#__PURE__*/jsx(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(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 = useTranslation(),
    t = _useTranslation.t;
  var isUpdatePermissionGranted = config.permissions.update;
  var _useState = useState(""),
    _useState2 = _slicedToArray(_useState, 2),
    alertType = _useState2[0],
    setAlertType = _useState2[1];
  var _useState3 = useState(""),
    _useState4 = _slicedToArray(_useState3, 2),
    bulkUpdateRole = _useState4[0],
    setBulkUpdateRole = _useState4[1];
  var hasSelectedRows = 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 ? taxonomies.member.plural : 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 = useBulkUpdateMembers({
      onSuccess: function onSuccess() {
        var _config$bulkUpdateMem;
        setSelectedRows(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(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 = 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__*/jsxs("div", {
    className: "flex items-center gap-4",
    children: [/*#__PURE__*/jsx(Typography, {
      "data-testid": "ntm-filtered-members-count",
      variant: "h6",
      children: /*#__PURE__*/jsx(Trans, {
        components: {
          span: /*#__PURE__*/jsx("span", {
            className: "text-muted-foreground"
          })
        },
        values: selectedMembersCountValues,
        i18nKey: hasSelectedRows ? "neetoTeamMembers.helpers.selectedMembersCount" : "neetoTeamMembers.helpers.metaNameWithCount"
      })
    }), hasSelectedRows && /*#__PURE__*/jsx(Tooltip, {
      content: !isUpdatePermissionGranted ? t("neetoTeamMembers.tooltips.noPermissionToEditMembers") : null,
      children: /*#__PURE__*/jsx("span", {
        children: /*#__PURE__*/jsxs(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__*/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__*/jsx(DropdownMenu.MenuItem, {
            "data-testid": "ntm-deactivate-members-button",
            isDisabled: !isUpdatePermissionGranted,
            onClick: function onClick() {
              return setAlertType("remove");
            },
            children: t("neetoTeamMembers.common.remove")
          })]
        })
      })
    }), /*#__PURE__*/jsx(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__*/jsx(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 = 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__*/jsx(SubHeader$1.RightBlock, {
    columnsButtonProps: {
      columnData: columns,
      fixedColumns: FIXED_COLUMNS,
      tableKey: 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: t("neetoTeamMembers.labels.exports.xlsx"),
  bulkExportLabel: t("neetoTeamMembers.labels.exportAs", {
    format: t("neetoTeamMembers.labels.exports.xlsx")
  }),
  dataTestid: "download-as-excel-radio-item"
}, {
  type: EXPORT_TYPES.CSV,
  individualExportLabel: t("neetoTeamMembers.labels.exports.csv"),
  bulkExportLabel: t("neetoTeamMembers.labels.exportAs", {
    format: t("neetoTeamMembers.labels.exports.csv")
  }),
  dataTestid: "download-as-csv-radio-item"
}, {
  type: EXPORT_TYPES.PDF,
  individualExportLabel: t("neetoTeamMembers.labels.exports.pdf"),
  bulkExportLabel: t("neetoTeamMembers.labels.exportAs", {
    format: 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(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 = useState(DEFAULT_EXPORT_OPTIONS),
    _useState2 = _slicedToArray(_useState, 2),
    exportOptions = _useState2[0],
    setExportOptions = _useState2[1];
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var setExportOption = function setExportOption(options) {
    return setExportOptions(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 = useExportMembers({
      onSuccess: function onSuccess() {
        var _globalProps$user;
        onClose();
        setExportOptions(DEFAULT_EXPORT_OPTIONS);
        toast.success(/*#__PURE__*/jsx(Trans, {
          i18nKey: "toastr.success.exportMembers",
          values: {
            email: (_globalProps$user = globalProps.user) === null || _globalProps$user === void 0 ? void 0 : _globalProps$user.email
          }
        }));
        captureAnalyticsEvent(EVENTS.TEAM_MEMBERS_DOWNLOADED, _objectSpread$2({}, exportOptions));
      },
      onError: function onError(error) {
        return toast.error(error.message);
      }
    }),
    exportMembers = _useExportMembers.mutate;
  var description = isNotEmpty(selectedMemberIds) || hasBulkSelectedAllRows ? t("neetoTeamMembers.exportPane.description.selectedMembers", {
    count: selectedRowsCount
  }) : t("neetoTeamMembers.exportPane.description.allMembers");
  return /*#__PURE__*/jsxs(Sheet, {
    isOpen: isOpen,
    onClose: onClose,
    children: [/*#__PURE__*/jsx(Sheet.Header, {
      children: /*#__PURE__*/jsx(Sheet.Title, {
        "data-testid": "export-member-heading",
        children: t("neetoTeamMembers.exportPane.title")
      })
    }), /*#__PURE__*/jsx(Sheet.Body, {
      children: /*#__PURE__*/jsxs("div", {
        className: "space-y-4",
        children: [/*#__PURE__*/jsx(Typography, {
          variant: "body3",
          children: description
        }), /*#__PURE__*/jsx(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__*/jsx(RadioGroup.Item, {
              "data-testid": dataTestid,
              id: type,
              label: bulkExportLabel,
              value: type
            }, type);
          })
        })]
      })
    }), /*#__PURE__*/jsxs(Sheet.Footer, {
      className: "gap-x-2",
      children: [/*#__PURE__*/jsx(Button, {
        "data-testid": "export-submit-button",
        onClick: function onClick() {
          return exportMembers({
            "export": getParams()
          });
        },
        children: t("neetoTeamMembers.buttons.export")
      }), /*#__PURE__*/jsx(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(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$1 = function Header(_ref) {
  var _config$header, _config$header2;
  var config = _ref.config,
    setIsOpen = _ref.setIsOpen,
    searchProps = _ref.searchProps;
  return /*#__PURE__*/jsx(NeetoHeader, _objectSpread$1({
    searchProps: searchProps,
    title: taxonomies.member.plural,
    actionBlock: /*#__PURE__*/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(assoc("manageMember", true));
      }
    })
  }, config === null || config === void 0 || (_config$header2 = config.header) === null || _config$header2 === void 0 ? void 0 : _config$header2.otherProps));
};
var Header = /*#__PURE__*/memo(Header$1);

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 TeamMembers = function TeamMembers(_ref) {
  var _config$fetchApiRespo, _config$table, _config$table$onDropd, _config$table2, _filters$pageSize3;
  var config = _ref.config;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var history = useHistory();
  var _useBreakpoints = useBreakpoints(),
    isSize = _useBreakpoints.isSize;
  var queryParams = useQueryParams();
  var isViewPermissionGranted = config.permissions.view;
  var isCreatePermissionGranted = config.permissions.create;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isFiltersPaneOpen = _useState2[0],
    setIsFiltersPaneOpen = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isDownloadPaneOpen = _useState4[0],
    setIsDownloadPaneOpen = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    hasBulkSelectedAllRows = _useState6[0],
    setHasBulkSelectedAllRows = _useState6[1];
  useEffect(function () {
    handleMemberFilterChange();
  }, []);
  var _useFilters = useFilters({
      config: config
    }),
    filters = _useFilters.filters,
    setFilters = _useFilters.setFilters,
    filterColumns = _useFilters.filterColumns,
    searchProps = _useFilters.searchProps,
    searchKeywordProps = _useFilters.searchKeywordProps;
  var _useFetchMembers = useFetchMembers(_objectSpread({}, filters), {
      enabled: isViewPermissionGranted
    }),
    team = _useFetchMembers.data,
    isMembersLoading = _useFetchMembers.isLoading,
    isMembersFetching = _useFetchMembers.isFetching;
  var bulkParams = {
    neetoFilters: filters["neetoFilters"],
    considerAllTeamMembers: hasBulkSelectedAllRows
  };
  var _useFetchRoles = useFetchRoles({
      select: function select(response) {
        var _response$organizatio;
        return 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 = useUpdateMember({
      onSuccess: function onSuccess() {
        var _filters$pageSize, _config$updateMember;
        handleAlertClose();
        handlePageChange(setFilters, history)(DEFAULT_PAGE_INDEX, (_filters$pageSize = filters.pageSize) !== null && _filters$pageSize !== void 0 ? _filters$pageSize : 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 = getFilteredRoles(roles, config);
  var _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 = useMemo(function () {
    return 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 = useTableConfigurations(TABLE_KEYS.TEAM_MEMBERS_TABLE, columns),
    isTableConfigurationLoading = _useTableConfiguratio.isTableConfigurationLoading,
    customizedColumns = _useTableConfiguratio.customizedColumns,
    hideColumn = _useTableConfiguratio.hideColumn;
  var handleNeetoFilterChange = function handleNeetoFilterChange(filters) {
    setFilters(mergeLeft({
      neetoFilters: filters,
      page: DEFAULT_PAGE_INDEX
    }));
    setSelectedRows(DEFAULT_SELECTED_ROWS);
    history.push(buildUrl(window.location.pathname, mergeLeft({
      page: DEFAULT_PAGE_INDEX
    }, queryParams)));
  };
  var _generateNoDataConten = generateNoDataContent({
      buttonProps: {
        onClick: function onClick() {
          return setIsOpen(assoc("manageMember", true));
        },
        disabled: !isCreatePermissionGranted
      }
    }),
    noDataTitle = _generateNoDataConten.noDataTitle,
    noDataDescription = _generateNoDataConten.noDataDescription,
    noDataIcon = _generateNoDataConten.noDataIcon,
    noDataButtonProps = _generateNoDataConten.noDataButtonProps;
  if (isRolesLoading || isMembersLoading) {
    return /*#__PURE__*/jsx("div", {
      className: "flex h-full min-h-screen w-full items-center justify-center",
      children: /*#__PURE__*/jsx(Spinner, {})
    });
  }
  return /*#__PURE__*/jsxs(Fragment, {
    children: [/*#__PURE__*/jsxs(Container, {
      className: "pb-10",
      children: [/*#__PURE__*/jsx(Header, {
        config: config,
        setIsOpen: setIsOpen,
        searchProps: hasMembers ? searchProps : null
      }), /*#__PURE__*/jsx(SubHeader$1, {
        className: "mb-4",
        leftActionBlock: hasMembers && /*#__PURE__*/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 handlePageChange(setFilters, history)(DEFAULT_PAGE_INDEX, (_filters$pageSize2 = filters.pageSize) !== null && _filters$pageSize2 !== void 0 ? _filters$pageSize2 : DEFAULT_PAGE_SIZE);
          }
        }),
        rightActionBlock: hasMembers && /*#__PURE__*/jsx(SubHeader.Right, {
          columns: columns,
          filterColumns: filterColumns,
          handleNeetoFilterChange: handleNeetoFilterChange,
          isFiltersPaneOpen: isFiltersPaneOpen,
          searchKeywordProps: searchKeywordProps,
          setIsDownloadPaneOpen: setIsDownloadPaneOpen,
          setIsFiltersPaneOpen: setIsFiltersPaneOpen
        })
      }), /*#__PURE__*/jsx(FiltersBar, {
        className: "mb-4",
        columns: filterColumns,
        keyword: searchKeywordProps,
        setIsPaneOpen: setIsFiltersPaneOpen,
        onChange: handleNeetoFilterChange
      }), /*#__PURE__*/jsx(ExportPane, {
        hasBulkSelectedAllRows: hasBulkSelectedAllRows,
        selectedRowsCount: selectedRowsCount,
        appliedFilters: filters,
        isOpen: isDownloadPaneOpen,
        selectedMemberIds: selectedRows.keys,
        onClose: function onClose() {
          return setIsDownloadPaneOpen(false);
        }
      }), !hasMembers ? /*#__PURE__*/jsx("div", {
        className: "flex w-full flex-1 items-center justify-center",
        children: /*#__PURE__*/jsx(Empty, {
          description: noDataDescription,
          icon: noDataIcon,
          primaryButtonProps: noDataButtonProps,
          title: noDataTitle
        })
      }) : (team === null || team === void 0 ? void 0 : team.membersCount) === 0 ? /*#__PURE__*/jsx("div", {
        className: "flex w-full flex-1 items-center justify-center",
        children: /*#__PURE__*/jsx(Empty, {
          icon: Search,
          description: t("neetoTeamMembers.common.memberSearchEmptyDescription"),
          title: t("neetoTeamMembers.common.memberSearchEmptyTitle", {
            what: taxonomies.member.plural
          })
        })
      }) : /*#__PURE__*/jsx(DataTable, {
        enableSorting: true,
        fixedHeight: true,
        allowRowClick: false,
        columns: customizedColumns,
        currentPage: parseInt(filters.page, 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 : 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: handlePageChange(setFilters, history),
        onRowSelect: handleRowSelect,
        onSort: handleTableChange
      })]
    }), /*#__PURE__*/jsx(ManageMember, {
      config: config,
      selectedMember: selectedMember,
      componentConfig: {
        isOpen: isOpen.manageMember
      },
      roles: filteredRoles,
      onComplete: handlePaneClose
    }), /*#__PURE__*/jsx(Alert, {
      cancelButtonLabel: t("neetoTeamMembers.buttons.cancel"),
      isOpen: isOpen.alert,
      isSubmitting: isUpdatingMember,
      message: renderUpdateAlert("message", updateMemberAlertProps),
      submitButtonLabel: t("neetoTeamMembers.buttons.remove"),
      title: renderUpdateAlert("title", updateMemberAlertProps),
      onClose: handleAlertClose,
      onSubmit: handleRemoveMember
    })]
  });
};
var index = withTitle(withReactQuery(TeamMembers), taxonomies.member.plural);

export { index as default };
//# sourceMappingURL=TeamMembers.js.map
