"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const helperPlugin = require("@strapi/helper-plugin");
const reactRedux = require("react-redux");
const AuthenticatedApp = require("./AuthenticatedApp-bb793364.js");
const React = require("react");
const designSystem = require("@strapi/design-system");
const Icons = require("@strapi/icons");
const reactIntl = require("react-intl");
const reactRouterDom = require("react-router-dom");
const useAdminRoles = require("./useAdminRoles-68d5d608.js");
const PropTypes = require("prop-types");
const produce = require("immer");
require("react-query");
require("semver/functions/lt");
require("semver/functions/valid");
require("./index-3649838b.js");
require("react-dom/client");
require("invariant");
require("lodash/isFunction");
require("lodash/merge");
require("lodash/pick");
require("react-helmet");
require("@radix-ui/react-context");
require("@strapi/design-system/v2");
require("formik");
require("lodash/camelCase");
require("styled-components");
require("yup");
require("lodash/defaultsDeep");
require("lodash/omit");
require("qs");
require("lodash/get");
require("lodash/set");
require("@reduxjs/toolkit");
require("react-dnd");
require("react-dnd-html5-backend");
require("lodash/cloneDeep");
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
const PropTypes__default = /* @__PURE__ */ _interopDefault(PropTypes);
const produce__default = /* @__PURE__ */ _interopDefault(produce);
const EmptyRole = () => "todo empty role";
const RoleRow = ({ id, name, description, usersCount, icons, rowIndex, canUpdate }) => {
  const { formatMessage } = reactIntl.useIntl();
  const [, editObject] = icons;
  const usersCountText = formatMessage(
    {
      id: `Roles.RoleRow.user-count`,
      defaultMessage: "{number, plural, =0 {#  user} one {#  user} other {# users}}"
    },
    { number: usersCount }
  );
  return /* @__PURE__ */ jsxRuntime.jsxs(
    designSystem.Tr,
    {
      "aria-rowindex": rowIndex,
      ...canUpdate ? helperPlugin.onRowClick({
        fn: editObject.onClick
      }) : {},
      children: [
        /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { maxWidth: helperPlugin.pxToRem(130), children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { ellipsis: true, textColor: "neutral800", children: name }) }),
        /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { maxWidth: helperPlugin.pxToRem(250), children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { ellipsis: true, textColor: "neutral800", children: description }) }),
        /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral800", children: usersCountText }) }),
        /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "flex-end", ...helperPlugin.stopPropagation, children: icons.map(
          (icon, i) => icon ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { paddingLeft: i === 0 ? 0 : 1, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.IconButton, { onClick: icon.onClick, label: icon.label, noBorder: true, icon: icon.icon }) }, icon.label) : null
        ) }) })
      ]
    },
    id
  );
};
RoleRow.propTypes = {
  id: PropTypes__default.default.number.isRequired,
  name: PropTypes__default.default.string.isRequired,
  description: PropTypes__default.default.string.isRequired,
  usersCount: PropTypes__default.default.number.isRequired,
  icons: PropTypes__default.default.array.isRequired,
  rowIndex: PropTypes__default.default.number.isRequired,
  canUpdate: PropTypes__default.default.bool
};
RoleRow.defaultProps = {
  canUpdate: false
};
const initialState = {
  roleToDelete: null,
  showModalConfirmButtonLoading: false,
  shouldRefetchData: false
};
const reducer = (state, action) => produce__default.default(state, (draftState) => {
  switch (action.type) {
    case "ON_REMOVE_ROLES": {
      draftState.showModalConfirmButtonLoading = true;
      break;
    }
    case "ON_REMOVE_ROLES_SUCCEEDED": {
      draftState.shouldRefetchData = true;
      draftState.roleToDelete = null;
      break;
    }
    case "RESET_DATA_TO_DELETE": {
      draftState.shouldRefetchData = false;
      draftState.roleToDelete = null;
      draftState.showModalConfirmButtonLoading = false;
      break;
    }
    case "SET_ROLE_TO_DELETE": {
      draftState.roleToDelete = action.id;
      break;
    }
    default:
      return draftState;
  }
});
const useRoleActions = ({ canCreate, canDelete, canUpdate, refetchRoles }) => {
  const { formatMessage } = reactIntl.useIntl();
  const { formatAPIError } = helperPlugin.useAPIErrorHandler();
  const toggleNotification = helperPlugin.useNotification();
  const [isWarningDeleteAllOpened, setIsWarningDeleteAllOpenend] = React.useState(false);
  const { push } = reactRouterDom.useHistory();
  const [{ selectedRoles, showModalConfirmButtonLoading, roleToDelete }, dispatch] = React.useReducer(
    reducer,
    initialState
  );
  const { post } = helperPlugin.getFetchClient();
  const handleDeleteData = async () => {
    try {
      dispatch({
        type: "ON_REMOVE_ROLES"
      });
      await post("/admin/roles/batch-delete", {
        ids: [roleToDelete]
      });
      await refetchRoles();
      dispatch({
        type: "RESET_DATA_TO_DELETE"
      });
    } catch (error) {
      toggleNotification({
        type: "warning",
        message: formatAPIError(error)
      });
    }
    handleToggleModal();
  };
  const onRoleDuplicate = React.useCallback(
    (id) => {
      push(`/settings/roles/duplicate/${id}`);
    },
    [push]
  );
  const handleNewRoleClick = () => push("/settings/roles/new");
  const onRoleRemove = React.useCallback((roleId) => {
    dispatch({
      type: "SET_ROLE_TO_DELETE",
      id: roleId
    });
    handleToggleModal();
  }, []);
  const handleToggleModal = () => setIsWarningDeleteAllOpenend((prev) => !prev);
  const handleGoTo = React.useCallback(
    (id) => {
      push(`/settings/roles/${id}`);
    },
    [push]
  );
  const handleClickDelete = React.useCallback(
    (e, role) => {
      e.preventDefault();
      e.stopPropagation();
      if (role.usersCount) {
        toggleNotification({
          type: "info",
          message: { id: "Roles.ListPage.notification.delete-not-allowed" }
        });
      } else {
        onRoleRemove(role.id);
      }
    },
    [toggleNotification, onRoleRemove]
  );
  const handleClickDuplicate = React.useCallback(
    (e, role) => {
      e.preventDefault();
      e.stopPropagation();
      onRoleDuplicate(role.id);
    },
    [onRoleDuplicate]
  );
  const getIcons = React.useCallback(
    (role) => [
      ...canCreate ? [
        {
          onClick: (e) => handleClickDuplicate(e, role),
          label: formatMessage({ id: "app.utils.duplicate", defaultMessage: "Duplicate" }),
          icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Duplicate, {})
        }
      ] : [],
      ...canUpdate ? [
        {
          onClick: () => handleGoTo(role.id),
          label: formatMessage({ id: "app.utils.edit", defaultMessage: "Edit" }),
          icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Pencil, {})
        }
      ] : [],
      ...canDelete ? [
        {
          onClick: (e) => handleClickDelete(e, role),
          label: formatMessage({ id: "global.delete", defaultMessage: "Delete" }),
          icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Trash, {})
        }
      ] : []
    ],
    [
      formatMessage,
      handleClickDelete,
      handleClickDuplicate,
      handleGoTo,
      canCreate,
      canUpdate,
      canDelete
    ]
  );
  return {
    handleNewRoleClick,
    getIcons,
    selectedRoles,
    isWarningDeleteAllOpened,
    showModalConfirmButtonLoading,
    handleToggleModal,
    handleDeleteData
  };
};
const RoleListPage = () => {
  const { formatMessage } = reactIntl.useIntl();
  helperPlugin.useFocusWhenNavigate();
  const permissions = reactRedux.useSelector(AuthenticatedApp.selectAdminPermissions);
  const [{ query }] = helperPlugin.useQueryParams();
  const {
    isLoading: isLoadingForPermissions,
    allowedActions: { canCreate, canDelete, canRead, canUpdate }
  } = helperPlugin.useRBAC(permissions.settings.roles);
  const {
    roles,
    isLoading,
    refetch: refetchRoles
  } = useAdminRoles.useAdminRoles(
    { filters: query?._q ? { name: { $containsi: query._q } } : void 0 },
    {
      cacheTime: 0,
      enabled: !isLoadingForPermissions && canRead
    }
  );
  const {
    handleNewRoleClick,
    getIcons,
    isWarningDeleteAllOpened,
    showModalConfirmButtonLoading,
    handleToggleModal,
    handleDeleteData
  } = useRoleActions({ refetchRoles, canCreate, canDelete, canUpdate });
  const rowCount = roles.length + 1;
  const colCount = 6;
  if (isLoadingForPermissions) {
    return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Main, { children: /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.LoadingIndicatorPage, {}) });
  }
  const title = formatMessage({
    id: "global.roles",
    defaultMessage: "roles"
  });
  return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Main, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.SettingsPageTitle, { name: "Roles" }),
    /* @__PURE__ */ jsxRuntime.jsx(
      designSystem.HeaderLayout,
      {
        primaryAction: canCreate ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { onClick: handleNewRoleClick, startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Plus, {}), size: "S", children: formatMessage({
          id: "Settings.roles.list.button.add",
          defaultMessage: "Add new role"
        }) }) : null,
        title,
        subtitle: formatMessage({
          id: "Settings.roles.list.description",
          defaultMessage: "List of roles"
        }),
        as: "h2"
      }
    ),
    canRead && /* @__PURE__ */ jsxRuntime.jsx(
      designSystem.ActionLayout,
      {
        startActions: /* @__PURE__ */ jsxRuntime.jsx(
          helperPlugin.SearchURLQuery,
          {
            label: formatMessage(
              { id: "app.component.search.label", defaultMessage: "Search for {target}" },
              { target: title }
            )
          }
        )
      }
    ),
    canRead && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.ContentLayout, { children: [
      /* @__PURE__ */ jsxRuntime.jsxs(
        designSystem.Table,
        {
          colCount,
          rowCount,
          footer: canCreate ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.TFooter, { onClick: handleNewRoleClick, icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Plus, {}), children: formatMessage({
            id: "Settings.roles.list.button.add",
            defaultMessage: "Add new role"
          }) }) : null,
          children: [
            /* @__PURE__ */ jsxRuntime.jsx(designSystem.Thead, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Tr, { "aria-rowindex": 1, children: [
              /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: formatMessage({
                id: "global.name",
                defaultMessage: "Name"
              }) }) }),
              /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: formatMessage({
                id: "global.description",
                defaultMessage: "Description"
              }) }) }),
              /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: formatMessage({
                id: "global.users",
                defaultMessage: "Users"
              }) }) }),
              /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.VisuallyHidden, { children: formatMessage({
                id: "global.actions",
                defaultMessage: "Actions"
              }) }) })
            ] }) }),
            /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tbody, { children: roles?.map((role, index) => /* @__PURE__ */ jsxRuntime.jsx(
              RoleRow,
              {
                id: role.id,
                name: role.name,
                description: role.description,
                usersCount: role.usersCount,
                icons: getIcons(role),
                rowIndex: index + 2,
                canUpdate
              },
              role.id
            )) })
          ]
        }
      ),
      !rowCount && !isLoading && /* @__PURE__ */ jsxRuntime.jsx(EmptyRole, {})
    ] }),
    /* @__PURE__ */ jsxRuntime.jsx(
      helperPlugin.ConfirmDialog,
      {
        isOpen: isWarningDeleteAllOpened,
        onConfirm: handleDeleteData,
        isConfirmButtonLoading: showModalConfirmButtonLoading,
        onToggleDialog: handleToggleModal
      }
    )
  ] });
};
const ProtectedListPage = () => {
  const permissions = reactRedux.useSelector(AuthenticatedApp.selectAdminPermissions);
  return /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.CheckPagePermissions, { permissions: permissions.settings.roles.main, children: /* @__PURE__ */ jsxRuntime.jsx(RoleListPage, {}) });
};
exports.default = ProtectedListPage;
//# sourceMappingURL=index-c42be44a.js.map
