"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const React = require("react");
const helperPlugin = require("@strapi/helper-plugin");
const reactRedux = require("react-redux");
const reactRouterDom = require("react-router-dom");
const AuthenticatedApp = require("./AuthenticatedApp-bb793364.js");
const designSystem = require("@strapi/design-system");
const Icons = require("@strapi/icons");
const formik = require("formik");
const get = require("lodash/get");
const omit = require("lodash/omit");
const pick = require("lodash/pick");
const PropTypes = require("prop-types");
const reactIntl = require("react-intl");
const useAdminUsers = require("./useAdminUsers-05d6b26a.js");
const index = require("./index-3649838b.js");
const formatAPIErrors = require("./formatAPIErrors-b599cf27.js");
const index$1 = require("./index-6b7ef4cc.js");
const edit = require("./edit-29bdf5d6.js");
require("react-query");
require("semver/functions/lt");
require("semver/functions/valid");
require("immer");
require("lodash/set");
require("react-dnd");
require("react-dnd-html5-backend");
require("@strapi/design-system/v2");
require("styled-components");
require("lodash/cloneDeep");
require("react-dom/client");
require("invariant");
require("lodash/isFunction");
require("lodash/merge");
require("react-helmet");
require("@radix-ui/react-context");
require("lodash/camelCase");
require("yup");
require("lodash/defaultsDeep");
require("qs");
require("@reduxjs/toolkit");
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
const React__default = /* @__PURE__ */ _interopDefault(React);
const get__default = /* @__PURE__ */ _interopDefault(get);
const omit__default = /* @__PURE__ */ _interopDefault(omit);
const pick__default = /* @__PURE__ */ _interopDefault(pick);
const PropTypes__default = /* @__PURE__ */ _interopDefault(PropTypes);
const putUser = async (id, body) => {
  const { put } = helperPlugin.getFetchClient();
  const { data } = await put(`/admin/users/${id}`, body);
  return data.data;
};
const layout = [
  [
    {
      intlLabel: {
        id: "Auth.form.firstname.label",
        defaultMessage: "First name"
      },
      name: "firstname",
      placeholder: {
        id: "Auth.form.firstname.placeholder",
        defaultMessage: "e.g. Kai"
      },
      type: "text",
      size: {
        col: 6,
        xs: 12
      },
      required: true
    },
    {
      intlLabel: {
        id: "Auth.form.lastname.label",
        defaultMessage: "Last name"
      },
      name: "lastname",
      placeholder: {
        id: "Auth.form.lastname.placeholder",
        defaultMessage: "e.g. Doe"
      },
      type: "text",
      size: {
        col: 6,
        xs: 12
      }
    }
  ],
  [
    {
      intlLabel: {
        id: "Auth.form.email.label",
        defaultMessage: "Email"
      },
      name: "email",
      placeholder: {
        id: "Auth.form.email.placeholder",
        defaultMessage: "e.g. kai.doe@strapi.io"
      },
      type: "email",
      size: {
        col: 6,
        xs: 12
      },
      required: true
    },
    {
      intlLabel: {
        id: "Auth.form.username.label",
        defaultMessage: "Username"
      },
      name: "username",
      placeholder: {
        id: "Auth.form.username.placeholder",
        defaultMessage: "e.g. Kai_Doe"
      },
      type: "text",
      size: {
        col: 6,
        xs: 12
      }
    }
  ],
  [
    {
      intlLabel: {
        id: "global.password",
        defaultMessage: "Password"
      },
      name: "password",
      type: "password",
      size: {
        col: 6,
        xs: 12
      },
      autoComplete: "new-password"
    },
    {
      intlLabel: {
        id: "Auth.form.confirmPassword.label",
        defaultMessage: "Password confirmation"
      },
      name: "confirmPassword",
      type: "password",
      size: {
        col: 6,
        xs: 12
      },
      autoComplete: "new-password"
    }
  ],
  [
    {
      intlLabel: {
        id: "Auth.form.active.label",
        defaultMessage: "Active"
      },
      name: "isActive",
      type: "bool",
      size: {
        col: 6,
        xs: 12
      }
    }
  ]
];
const fieldsToPick = ["email", "firstname", "lastname", "username", "isActive", "roles"];
const EditPage = ({ canUpdate }) => {
  const { formatMessage } = reactIntl.useIntl();
  const {
    params: { id }
  } = reactRouterDom.useRouteMatch("/settings/users/:id");
  const { push } = reactRouterDom.useHistory();
  const { setUserDisplayName } = helperPlugin.useAppInfo();
  const toggleNotification = helperPlugin.useNotification();
  const { lockApp, unlockApp } = helperPlugin.useOverlayBlocker();
  const MagicLink = index.useEnterprise(
    index$1.MagicLinkCE,
    async () => (await Promise.resolve().then(() => require("./index-b5ad91e9.js"))).MagicLinkEE
  );
  helperPlugin.useFocusWhenNavigate();
  const {
    users: [user],
    isLoading: isLoadingAdminUsers
  } = useAdminUsers.useAdminUsers(
    { id },
    {
      cacheTime: 0,
      onError(error) {
        const { status } = error.response;
        if (status === 403) {
          toggleNotification({
            type: "info",
            message: {
              id: "notification.permission.not-allowed-read",
              defaultMessage: "You are not allowed to see this document"
            }
          });
          push("/");
        } else {
          toggleNotification({
            type: "warning",
            message: { id: "notification.error", defaultMessage: "An error occured" }
          });
        }
      }
    }
  );
  const handleSubmit = async (body, actions) => {
    lockApp();
    try {
      const data = await putUser(id, omit__default.default(body, "confirmPassword"));
      toggleNotification({
        type: "success",
        message: formatMessage({ id: "notification.success.saved", defaultMessage: "Saved" })
      });
      const userInfos = helperPlugin.auth.getUserInfo();
      if (id.toString() === userInfos.id.toString()) {
        helperPlugin.auth.setUserInfo(data);
        const userDisplayName = get__default.default(body, "username") || AuthenticatedApp.getFullName(body.firstname, body.lastname);
        setUserDisplayName(userDisplayName);
      }
      actions.setValues(pick__default.default(body, fieldsToPick));
    } catch (err) {
      const errors = formatAPIErrors.formatAPIErrors(err.response.data);
      const fieldsErrors = Object.keys(errors).reduce((acc, current) => {
        acc[current] = errors[current].id;
        return acc;
      }, {});
      actions.setErrors(fieldsErrors);
      toggleNotification({
        type: "warning",
        message: get__default.default(err, "response.data.error.message", "notification.error")
      });
    }
    unlockApp();
  };
  const isLoading = isLoadingAdminUsers || !MagicLink;
  const headerLabel = isLoading ? { id: "app.containers.Users.EditPage.header.label-loading", defaultMessage: "Edit user" } : { id: "app.containers.Users.EditPage.header.label", defaultMessage: "Edit {name}" };
  const initialData = Object.keys(pick__default.default(user, fieldsToPick)).reduce((acc, current) => {
    if (current === "roles") {
      acc[current] = (user?.roles || []).map(({ id: id2 }) => id2);
      return acc;
    }
    acc[current] = user?.[current];
    return acc;
  }, {});
  const headerLabelName = initialData.username || AuthenticatedApp.getFullName(initialData.firstname, initialData.lastname);
  const title = formatMessage(headerLabel, { name: headerLabelName });
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Main, { "aria-busy": "true", children: [
      /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.SettingsPageTitle, { name: "Users" }),
      /* @__PURE__ */ jsxRuntime.jsx(
        designSystem.HeaderLayout,
        {
          primaryAction: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { disabled: true, startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Check, {}), type: "button", size: "L", children: formatMessage({ id: "global.save", defaultMessage: "Save" }) }),
          title,
          navigationAction: /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.Link, { startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.ArrowLeft, {}), to: "/settings/users?pageSize=10&page=1&sort=firstname", children: formatMessage({
            id: "global.back",
            defaultMessage: "Back"
          }) })
        }
      ),
      /* @__PURE__ */ jsxRuntime.jsx(designSystem.ContentLayout, { children: /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.LoadingIndicatorPage, {}) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Main, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.SettingsPageTitle, { name: "Users" }),
    /* @__PURE__ */ jsxRuntime.jsx(
      formik.Formik,
      {
        onSubmit: handleSubmit,
        initialValues: initialData,
        validateOnChange: false,
        validationSchema: edit.schema$1,
        children: ({ errors, values, handleChange, isSubmitting, dirty }) => {
          return /* @__PURE__ */ jsxRuntime.jsxs(helperPlugin.Form, { children: [
            /* @__PURE__ */ jsxRuntime.jsx(
              designSystem.HeaderLayout,
              {
                primaryAction: /* @__PURE__ */ jsxRuntime.jsx(
                  designSystem.Button,
                  {
                    disabled: isSubmitting || !canUpdate ? true : !dirty,
                    startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Check, {}),
                    loading: isSubmitting,
                    type: "submit",
                    size: "L",
                    children: formatMessage({ id: "global.save", defaultMessage: "Save" })
                  }
                ),
                title,
                navigationAction: /* @__PURE__ */ jsxRuntime.jsx(
                  helperPlugin.Link,
                  {
                    startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.ArrowLeft, {}),
                    to: "/settings/users?pageSize=10&page=1&sort=firstname",
                    children: formatMessage({
                      id: "global.back",
                      defaultMessage: "Back"
                    })
                  }
                )
              }
            ),
            /* @__PURE__ */ jsxRuntime.jsxs(designSystem.ContentLayout, { children: [
              user?.registrationToken && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { paddingBottom: 6, children: /* @__PURE__ */ jsxRuntime.jsx(MagicLink, { registrationToken: user.registrationToken }) }),
              /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 7, children: [
                /* @__PURE__ */ jsxRuntime.jsx(
                  designSystem.Box,
                  {
                    background: "neutral0",
                    hasRadius: true,
                    shadow: "filterShadow",
                    paddingTop: 6,
                    paddingBottom: 6,
                    paddingLeft: 7,
                    paddingRight: 7,
                    children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
                      /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "delta", as: "h2", children: formatMessage({
                        id: "app.components.Users.ModalCreateBody.block-title.details",
                        defaultMessage: "Details"
                      }) }),
                      /* @__PURE__ */ jsxRuntime.jsx(designSystem.Grid, { gap: 5, children: layout.map((row) => {
                        return row.map((input) => {
                          return /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { ...input.size, children: /* @__PURE__ */ jsxRuntime.jsx(
                            helperPlugin.GenericInput,
                            {
                              ...input,
                              disabled: !canUpdate,
                              error: errors[input.name],
                              onChange: handleChange,
                              value: values[input.name] || ""
                            }
                          ) }, input.name);
                        });
                      }) })
                    ] })
                  }
                ),
                /* @__PURE__ */ jsxRuntime.jsx(
                  designSystem.Box,
                  {
                    background: "neutral0",
                    hasRadius: true,
                    shadow: "filterShadow",
                    paddingTop: 6,
                    paddingBottom: 6,
                    paddingLeft: 7,
                    paddingRight: 7,
                    children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
                      /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "delta", as: "h2", children: formatMessage({
                        id: "global.roles",
                        defaultMessage: "User's role"
                      }) }),
                      /* @__PURE__ */ jsxRuntime.jsx(designSystem.Grid, { gap: 5, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, xs: 12, children: /* @__PURE__ */ jsxRuntime.jsx(
                        index$1.SelectRoles,
                        {
                          disabled: !canUpdate,
                          error: errors.roles,
                          onChange: handleChange,
                          value: values.roles
                        }
                      ) }) })
                    ] })
                  }
                )
              ] })
            ] })
          ] });
        }
      }
    )
  ] });
};
EditPage.propTypes = {
  canUpdate: PropTypes__default.default.bool.isRequired
};
const ProtectedEditPage = () => {
  const toggleNotification = helperPlugin.useNotification();
  const permissions = reactRedux.useSelector(AuthenticatedApp.selectAdminPermissions);
  const memoizedPermissions = React__default.default.useMemo(
    () => ({
      read: permissions.settings.users.read,
      update: permissions.settings.users.update
    }),
    [permissions.settings.users]
  );
  const {
    isLoading,
    allowedActions: { canRead, canUpdate }
  } = helperPlugin.useRBAC(memoizedPermissions);
  const { state } = reactRouterDom.useLocation();
  const from = state?.from ?? "/";
  React.useEffect(() => {
    if (!isLoading) {
      if (!canRead && !canUpdate) {
        toggleNotification({
          type: "info",
          message: {
            id: "notification.permission.not-allowed-read",
            defaultMessage: "You are not allowed to see this document"
          }
        });
      }
    }
  }, [isLoading, canRead, canUpdate, toggleNotification]);
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.LoadingIndicatorPage, {});
  }
  if (!canRead && !canUpdate) {
    return /* @__PURE__ */ jsxRuntime.jsx(reactRouterDom.Redirect, { to: from });
  }
  return /* @__PURE__ */ jsxRuntime.jsx(EditPage, { canUpdate });
};
exports.default = ProtectedEditPage;
//# sourceMappingURL=index-47cd65b8.js.map
