import { jsx, jsxs } from "react/jsx-runtime";
import { translatedErrors, useNotification, useFetchClient, useOverlayBlocker, useTracking, useAPIErrorHandler, SettingsPageTitle, Link, LoadingIndicatorPage, useRBAC } from "@strapi/helper-plugin";
import { useSelector } from "react-redux";
import { useRouteMatch, Redirect } from "react-router-dom";
import { s as selectAdminPermissions } from "./AuthenticatedApp-4e25ce97.mjs";
import { useState, useRef } from "react";
import { Box, Flex, Typography, Button, Grid, GridItem, TextInput, Textarea, Main, HeaderLayout, ContentLayout } from "@strapi/design-system";
import { ArrowLeft } from "@strapi/icons";
import { Formik } from "formik";
import { useIntl } from "react-intl";
import { u as useAdminRoles } from "./useAdminRoles-7ab5d521.mjs";
import { u as useAdminRolePermissionLayout, a as useAdminRolePermissions, P as Permissions } from "./useAdminRolePermissions-603a2709.mjs";
import PropTypes from "prop-types";
import * as yup from "yup";
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 "lodash/camelCase";
import "styled-components";
import "lodash/defaultsDeep";
import "lodash/omit";
import "qs";
import "immer";
import "lodash/get";
import "lodash/set";
import "@reduxjs/toolkit";
import "react-dnd";
import "react-dnd-html5-backend";
import "lodash/cloneDeep";
import "lodash/has";
import "lodash/isEmpty";
import "lodash/sortBy";
import "lodash/groupBy";
import "lodash/upperFirst";
import "lodash/flattenDeep";
import "lodash/isObject";
const RoleForm = ({ disabled, role, values, errors, onChange, onBlur }) => {
  const { formatMessage } = useIntl();
  return /* @__PURE__ */ jsx(Box, { background: "neutral0", padding: 6, shadow: "filterShadow", hasRadius: true, children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
    /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", children: [
      /* @__PURE__ */ jsxs(Box, { children: [
        /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Typography, { fontWeight: "bold", children: role ? role.name : formatMessage({
          id: "global.details",
          defaultMessage: "Details"
        }) }) }),
        /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Typography, { textColor: "neutral500", variant: "pi", children: role ? role.description : formatMessage({
          id: "Settings.roles.form.description",
          defaultMessage: "Name and description of the role"
        }) }) })
      ] }),
      /* @__PURE__ */ jsx(Button, { disabled: true, variant: "secondary", children: formatMessage(
        {
          id: "Settings.roles.form.button.users-with-role",
          defaultMessage: "{number, plural, =0 {# users} one {# user} other {# users}} with this role"
        },
        { number: role.usersCount }
      ) })
    ] }),
    /* @__PURE__ */ jsxs(Grid, { gap: 4, children: [
      /* @__PURE__ */ jsx(GridItem, { col: 6, children: /* @__PURE__ */ jsx(
        TextInput,
        {
          disabled,
          name: "name",
          error: errors.name && formatMessage({ id: errors.name }),
          label: formatMessage({
            id: "global.name",
            defaultMessage: "Name"
          }),
          onChange,
          onBlur,
          required: true,
          value: values.name || ""
        }
      ) }),
      /* @__PURE__ */ jsx(GridItem, { col: 6, children: /* @__PURE__ */ jsx(
        Textarea,
        {
          disabled,
          label: formatMessage({
            id: "global.description",
            defaultMessage: "Description"
          }),
          id: "description",
          error: errors.name && formatMessage({ id: errors.name }),
          onChange,
          onBlur,
          children: values.description || ""
        }
      ) })
    ] })
  ] }) });
};
RoleForm.defaultProps = {
  disabled: false,
  role: null,
  values: { name: "", description: "" }
};
RoleForm.propTypes = {
  disabled: PropTypes.bool,
  errors: PropTypes.object.isRequired,
  onBlur: PropTypes.func.isRequired,
  onChange: PropTypes.func.isRequired,
  role: PropTypes.object,
  values: PropTypes.object
};
const schema = yup.object().shape({
  name: yup.string().required(translatedErrors.required)
});
const EditPage = () => {
  const toggleNotification = useNotification();
  const { formatMessage } = useIntl();
  const {
    params: { id }
  } = useRouteMatch("/settings/roles/:id");
  const { put } = useFetchClient();
  const [isSubmitting, setIsSubmiting] = useState(false);
  const permissionsRef = useRef();
  const { lockApp, unlockApp } = useOverlayBlocker();
  const { trackUsage } = useTracking();
  const { formatAPIError } = useAPIErrorHandler();
  const { isLoading: isLoadingPermissionsLayout, data: permissionsLayout } = useAdminRolePermissionLayout(id, {
    cacheTime: 0
  });
  const {
    roles: [role = {}],
    isLoading: isRoleLoading,
    refetch: refetchRole
  } = useAdminRoles(
    { id },
    {
      cacheTime: 0
    }
  );
  const { permissions, isLoading: isLoadingPermissions } = useAdminRolePermissions(
    { id },
    {
      cacheTime: 0
    }
  );
  const handleEditRoleSubmit = async (data) => {
    try {
      lockApp();
      setIsSubmiting(true);
      const { permissionsToSend, didUpdateConditions } = permissionsRef.current.getPermissions();
      await put(`/admin/roles/${id}`, data);
      if (role.code !== "strapi-super-admin") {
        await put(`/admin/roles/${id}/permissions`, {
          permissions: permissionsToSend
        });
        if (didUpdateConditions) {
          trackUsage("didUpdateConditions");
        }
      }
      permissionsRef.current.setFormAfterSubmit();
      await refetchRole();
      toggleNotification({
        type: "success",
        message: { id: "notification.success.saved" }
      });
    } catch (error) {
      toggleNotification({
        type: "warning",
        message: formatAPIError(error)
      });
    } finally {
      setIsSubmiting(false);
      unlockApp();
    }
  };
  const isFormDisabled = !isRoleLoading && role.code === "strapi-super-admin";
  return /* @__PURE__ */ jsxs(Main, { children: [
    /* @__PURE__ */ jsx(SettingsPageTitle, { name: "Roles" }),
    /* @__PURE__ */ jsx(
      Formik,
      {
        enableReinitialize: true,
        initialValues: {
          name: role.name,
          description: role.description
        },
        onSubmit: handleEditRoleSubmit,
        validationSchema: schema,
        validateOnChange: false,
        children: ({ handleSubmit, values, errors, handleChange, handleBlur }) => /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, children: [
          /* @__PURE__ */ jsx(
            HeaderLayout,
            {
              primaryAction: /* @__PURE__ */ jsx(Flex, { gap: 2, children: /* @__PURE__ */ jsx(
                Button,
                {
                  disabled: role.code === "strapi-super-admin",
                  onClick: handleSubmit,
                  loading: isSubmitting,
                  size: "L",
                  children: formatMessage({
                    id: "global.save",
                    defaultMessage: "Save"
                  })
                }
              ) }),
              title: formatMessage({
                id: "Settings.roles.edit.title",
                defaultMessage: "Edit a role"
              }),
              subtitle: formatMessage({
                id: "Settings.roles.create.description",
                defaultMessage: "Define the rights given to the role"
              }),
              navigationAction: /* @__PURE__ */ jsx(Link, { startIcon: /* @__PURE__ */ jsx(ArrowLeft, {}), to: "/settings/roles", children: formatMessage({
                id: "global.back",
                defaultMessage: "Back"
              }) })
            }
          ),
          /* @__PURE__ */ jsx(ContentLayout, { children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 6, children: [
            /* @__PURE__ */ jsx(
              RoleForm,
              {
                isLoading: isRoleLoading || isLoadingPermissions,
                disabled: isFormDisabled,
                errors,
                values,
                onChange: handleChange,
                onBlur: handleBlur,
                role
              }
            ),
            !isLoadingPermissionsLayout && !isRoleLoading && !isLoadingPermissions ? /* @__PURE__ */ jsx(Box, { shadow: "filterShadow", hasRadius: true, children: /* @__PURE__ */ jsx(
              Permissions,
              {
                isFormDisabled,
                permissions,
                ref: permissionsRef,
                layout: permissionsLayout
              }
            ) }) : /* @__PURE__ */ jsx(Box, { background: "neutral0", padding: 6, shadow: "filterShadow", hasRadius: true, children: /* @__PURE__ */ jsx(LoadingIndicatorPage, {}) })
          ] }) })
        ] })
      }
    )
  ] });
};
const ProtectedEditPage = () => {
  const permissions = useSelector(selectAdminPermissions);
  const {
    isLoading,
    allowedActions: { canRead, canUpdate }
  } = useRBAC({
    read: permissions.settings.roles.read,
    update: permissions.settings.roles.update
  });
  if (isLoading) {
    return /* @__PURE__ */ jsx(LoadingIndicatorPage, {});
  }
  if (!canRead && !canUpdate) {
    return /* @__PURE__ */ jsx(Redirect, { to: "/" });
  }
  return /* @__PURE__ */ jsx(EditPage, {});
};
export {
  ProtectedEditPage as default
};
//# sourceMappingURL=index-6fab74f4.mjs.map
