import { jsxs, jsx } from "react/jsx-runtime";
import { onRowClick, pxToRem, stopPropagation, useFocusWhenNavigate, useQueryParams, useRBAC, LoadingIndicatorPage, SettingsPageTitle, SearchURLQuery, ConfirmDialog, useAPIErrorHandler, useNotification, getFetchClient, CheckPagePermissions } from "@strapi/helper-plugin";
import { useSelector } from "react-redux";
import { s as selectAdminPermissions } from "./AuthenticatedApp-4e25ce97.mjs";
import { useState, useReducer, useCallback } from "react";
import { Tr, Td, Typography, Flex, Box, IconButton, Main, HeaderLayout, Button, ActionLayout, ContentLayout, Table, TFooter, Thead, Th, VisuallyHidden, Tbody } from "@strapi/design-system";
import { Plus, Duplicate, Pencil, Trash } from "@strapi/icons";
import { useIntl } from "react-intl";
import { useHistory } from "react-router-dom";
import { u as useAdminRoles } from "./useAdminRoles-7ab5d521.mjs";
import PropTypes from "prop-types";
import produce from "immer";
import "react-query";
import "semver/functions/lt";
import "semver/functions/valid";
import "./index-466b22f5.mjs";
import "react-dom/client";
import "invariant";
import "lodash/isFunction";
import "lodash/merge";
import "lodash/pick";
import "react-helmet";
import "@radix-ui/react-context";
import "@strapi/design-system/v2";
import "formik";
import "lodash/camelCase";
import "styled-components";
import "yup";
import "lodash/defaultsDeep";
import "lodash/omit";
import "qs";
import "lodash/get";
import "lodash/set";
import "@reduxjs/toolkit";
import "react-dnd";
import "react-dnd-html5-backend";
import "lodash/cloneDeep";
const EmptyRole = () => "todo empty role";
const RoleRow = ({ id, name, description, usersCount, icons, rowIndex, canUpdate }) => {
  const { formatMessage } = 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__ */ jsxs(
    Tr,
    {
      "aria-rowindex": rowIndex,
      ...canUpdate ? onRowClick({
        fn: editObject.onClick
      }) : {},
      children: [
        /* @__PURE__ */ jsx(Td, { maxWidth: pxToRem(130), children: /* @__PURE__ */ jsx(Typography, { ellipsis: true, textColor: "neutral800", children: name }) }),
        /* @__PURE__ */ jsx(Td, { maxWidth: pxToRem(250), children: /* @__PURE__ */ jsx(Typography, { ellipsis: true, textColor: "neutral800", children: description }) }),
        /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(Typography, { textColor: "neutral800", children: usersCountText }) }),
        /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(Flex, { justifyContent: "flex-end", ...stopPropagation, children: icons.map(
          (icon, i) => icon ? /* @__PURE__ */ jsx(Box, { paddingLeft: i === 0 ? 0 : 1, children: /* @__PURE__ */ jsx(IconButton, { onClick: icon.onClick, label: icon.label, noBorder: true, icon: icon.icon }) }, icon.label) : null
        ) }) })
      ]
    },
    id
  );
};
RoleRow.propTypes = {
  id: PropTypes.number.isRequired,
  name: PropTypes.string.isRequired,
  description: PropTypes.string.isRequired,
  usersCount: PropTypes.number.isRequired,
  icons: PropTypes.array.isRequired,
  rowIndex: PropTypes.number.isRequired,
  canUpdate: PropTypes.bool
};
RoleRow.defaultProps = {
  canUpdate: false
};
const initialState = {
  roleToDelete: null,
  showModalConfirmButtonLoading: false,
  shouldRefetchData: false
};
const reducer = (state, action) => produce(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 } = useIntl();
  const { formatAPIError } = useAPIErrorHandler();
  const toggleNotification = useNotification();
  const [isWarningDeleteAllOpened, setIsWarningDeleteAllOpenend] = useState(false);
  const { push } = useHistory();
  const [{ selectedRoles, showModalConfirmButtonLoading, roleToDelete }, dispatch] = useReducer(
    reducer,
    initialState
  );
  const { post } = 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 = useCallback(
    (id) => {
      push(`/settings/roles/duplicate/${id}`);
    },
    [push]
  );
  const handleNewRoleClick = () => push("/settings/roles/new");
  const onRoleRemove = useCallback((roleId) => {
    dispatch({
      type: "SET_ROLE_TO_DELETE",
      id: roleId
    });
    handleToggleModal();
  }, []);
  const handleToggleModal = () => setIsWarningDeleteAllOpenend((prev) => !prev);
  const handleGoTo = useCallback(
    (id) => {
      push(`/settings/roles/${id}`);
    },
    [push]
  );
  const handleClickDelete = 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 = useCallback(
    (e, role) => {
      e.preventDefault();
      e.stopPropagation();
      onRoleDuplicate(role.id);
    },
    [onRoleDuplicate]
  );
  const getIcons = useCallback(
    (role) => [
      ...canCreate ? [
        {
          onClick: (e) => handleClickDuplicate(e, role),
          label: formatMessage({ id: "app.utils.duplicate", defaultMessage: "Duplicate" }),
          icon: /* @__PURE__ */ jsx(Duplicate, {})
        }
      ] : [],
      ...canUpdate ? [
        {
          onClick: () => handleGoTo(role.id),
          label: formatMessage({ id: "app.utils.edit", defaultMessage: "Edit" }),
          icon: /* @__PURE__ */ jsx(Pencil, {})
        }
      ] : [],
      ...canDelete ? [
        {
          onClick: (e) => handleClickDelete(e, role),
          label: formatMessage({ id: "global.delete", defaultMessage: "Delete" }),
          icon: /* @__PURE__ */ jsx(Trash, {})
        }
      ] : []
    ],
    [
      formatMessage,
      handleClickDelete,
      handleClickDuplicate,
      handleGoTo,
      canCreate,
      canUpdate,
      canDelete
    ]
  );
  return {
    handleNewRoleClick,
    getIcons,
    selectedRoles,
    isWarningDeleteAllOpened,
    showModalConfirmButtonLoading,
    handleToggleModal,
    handleDeleteData
  };
};
const RoleListPage = () => {
  const { formatMessage } = useIntl();
  useFocusWhenNavigate();
  const permissions = useSelector(selectAdminPermissions);
  const [{ query }] = useQueryParams();
  const {
    isLoading: isLoadingForPermissions,
    allowedActions: { canCreate, canDelete, canRead, canUpdate }
  } = useRBAC(permissions.settings.roles);
  const {
    roles,
    isLoading,
    refetch: refetchRoles
  } = 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__ */ jsx(Main, { children: /* @__PURE__ */ jsx(LoadingIndicatorPage, {}) });
  }
  const title = formatMessage({
    id: "global.roles",
    defaultMessage: "roles"
  });
  return /* @__PURE__ */ jsxs(Main, { children: [
    /* @__PURE__ */ jsx(SettingsPageTitle, { name: "Roles" }),
    /* @__PURE__ */ jsx(
      HeaderLayout,
      {
        primaryAction: canCreate ? /* @__PURE__ */ jsx(Button, { onClick: handleNewRoleClick, startIcon: /* @__PURE__ */ jsx(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__ */ jsx(
      ActionLayout,
      {
        startActions: /* @__PURE__ */ jsx(
          SearchURLQuery,
          {
            label: formatMessage(
              { id: "app.component.search.label", defaultMessage: "Search for {target}" },
              { target: title }
            )
          }
        )
      }
    ),
    canRead && /* @__PURE__ */ jsxs(ContentLayout, { children: [
      /* @__PURE__ */ jsxs(
        Table,
        {
          colCount,
          rowCount,
          footer: canCreate ? /* @__PURE__ */ jsx(TFooter, { onClick: handleNewRoleClick, icon: /* @__PURE__ */ jsx(Plus, {}), children: formatMessage({
            id: "Settings.roles.list.button.add",
            defaultMessage: "Add new role"
          }) }) : null,
          children: [
            /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { "aria-rowindex": 1, children: [
              /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: formatMessage({
                id: "global.name",
                defaultMessage: "Name"
              }) }) }),
              /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: formatMessage({
                id: "global.description",
                defaultMessage: "Description"
              }) }) }),
              /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: formatMessage({
                id: "global.users",
                defaultMessage: "Users"
              }) }) }),
              /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(VisuallyHidden, { children: formatMessage({
                id: "global.actions",
                defaultMessage: "Actions"
              }) }) })
            ] }) }),
            /* @__PURE__ */ jsx(Tbody, { children: roles?.map((role, index) => /* @__PURE__ */ 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__ */ jsx(EmptyRole, {})
    ] }),
    /* @__PURE__ */ jsx(
      ConfirmDialog,
      {
        isOpen: isWarningDeleteAllOpened,
        onConfirm: handleDeleteData,
        isConfirmButtonLoading: showModalConfirmButtonLoading,
        onToggleDialog: handleToggleModal
      }
    )
  ] });
};
const ProtectedListPage = () => {
  const permissions = useSelector(selectAdminPermissions);
  return /* @__PURE__ */ jsx(CheckPagePermissions, { permissions: permissions.settings.roles.main, children: /* @__PURE__ */ jsx(RoleListPage, {}) });
};
export {
  ProtectedListPage as default
};
//# sourceMappingURL=index-e50339c6.mjs.map
