import { jsxs, jsx } from "react/jsx-runtime";
import React__default, { useEffect } from "react";
import { getFetchClient, useAppInfo, useNotification, useOverlayBlocker, useFocusWhenNavigate, SettingsPageTitle, Link, LoadingIndicatorPage, Form, GenericInput, auth, useRBAC } from "@strapi/helper-plugin";
import { useSelector } from "react-redux";
import { useRouteMatch, useHistory, useLocation, Redirect } from "react-router-dom";
import { g as getFullName, s as selectAdminPermissions } from "./AuthenticatedApp-4e25ce97.mjs";
import { Main, HeaderLayout, Button, ContentLayout, Box, Flex, Typography, Grid, GridItem } from "@strapi/design-system";
import { Check, ArrowLeft } from "@strapi/icons";
import { Formik } from "formik";
import get from "lodash/get";
import omit from "lodash/omit";
import pick from "lodash/pick";
import PropTypes from "prop-types";
import { useIntl } from "react-intl";
import { u as useAdminUsers } from "./useAdminUsers-09f86a58.mjs";
import { p as useEnterprise } from "./index-466b22f5.mjs";
import { f as formatAPIErrors } from "./formatAPIErrors-db6ed675.mjs";
import { M as MagicLinkCE, S as SelectRoles } from "./index-2ed78f76.mjs";
import { a as schema } from "./edit-923cefa0.mjs";
import "react-query";
import "semver/functions/lt";
import "semver/functions/valid";
import "immer";
import "lodash/set";
import "react-dnd";
import "react-dnd-html5-backend";
import "@strapi/design-system/v2";
import "styled-components";
import "lodash/cloneDeep";
import "react-dom/client";
import "invariant";
import "lodash/isFunction";
import "lodash/merge";
import "react-helmet";
import "@radix-ui/react-context";
import "lodash/camelCase";
import "yup";
import "lodash/defaultsDeep";
import "qs";
import "@reduxjs/toolkit";
const putUser = async (id, body) => {
  const { put } = 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 } = useIntl();
  const {
    params: { id }
  } = useRouteMatch("/settings/users/:id");
  const { push } = useHistory();
  const { setUserDisplayName } = useAppInfo();
  const toggleNotification = useNotification();
  const { lockApp, unlockApp } = useOverlayBlocker();
  const MagicLink = useEnterprise(
    MagicLinkCE,
    async () => (await import("./index-ef863e33.mjs")).MagicLinkEE
  );
  useFocusWhenNavigate();
  const {
    users: [user],
    isLoading: isLoadingAdminUsers
  } = 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(body, "confirmPassword"));
      toggleNotification({
        type: "success",
        message: formatMessage({ id: "notification.success.saved", defaultMessage: "Saved" })
      });
      const userInfos = auth.getUserInfo();
      if (id.toString() === userInfos.id.toString()) {
        auth.setUserInfo(data);
        const userDisplayName = get(body, "username") || getFullName(body.firstname, body.lastname);
        setUserDisplayName(userDisplayName);
      }
      actions.setValues(pick(body, fieldsToPick));
    } catch (err) {
      const errors = 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(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(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 || getFullName(initialData.firstname, initialData.lastname);
  const title = formatMessage(headerLabel, { name: headerLabelName });
  if (isLoading) {
    return /* @__PURE__ */ jsxs(Main, { "aria-busy": "true", children: [
      /* @__PURE__ */ jsx(SettingsPageTitle, { name: "Users" }),
      /* @__PURE__ */ jsx(
        HeaderLayout,
        {
          primaryAction: /* @__PURE__ */ jsx(Button, { disabled: true, startIcon: /* @__PURE__ */ jsx(Check, {}), type: "button", size: "L", children: formatMessage({ id: "global.save", defaultMessage: "Save" }) }),
          title,
          navigationAction: /* @__PURE__ */ jsx(Link, { startIcon: /* @__PURE__ */ jsx(ArrowLeft, {}), to: "/settings/users?pageSize=10&page=1&sort=firstname", children: formatMessage({
            id: "global.back",
            defaultMessage: "Back"
          }) })
        }
      ),
      /* @__PURE__ */ jsx(ContentLayout, { children: /* @__PURE__ */ jsx(LoadingIndicatorPage, {}) })
    ] });
  }
  return /* @__PURE__ */ jsxs(Main, { children: [
    /* @__PURE__ */ jsx(SettingsPageTitle, { name: "Users" }),
    /* @__PURE__ */ jsx(
      Formik,
      {
        onSubmit: handleSubmit,
        initialValues: initialData,
        validateOnChange: false,
        validationSchema: schema,
        children: ({ errors, values, handleChange, isSubmitting, dirty }) => {
          return /* @__PURE__ */ jsxs(Form, { children: [
            /* @__PURE__ */ jsx(
              HeaderLayout,
              {
                primaryAction: /* @__PURE__ */ jsx(
                  Button,
                  {
                    disabled: isSubmitting || !canUpdate ? true : !dirty,
                    startIcon: /* @__PURE__ */ jsx(Check, {}),
                    loading: isSubmitting,
                    type: "submit",
                    size: "L",
                    children: formatMessage({ id: "global.save", defaultMessage: "Save" })
                  }
                ),
                title,
                navigationAction: /* @__PURE__ */ jsx(
                  Link,
                  {
                    startIcon: /* @__PURE__ */ jsx(ArrowLeft, {}),
                    to: "/settings/users?pageSize=10&page=1&sort=firstname",
                    children: formatMessage({
                      id: "global.back",
                      defaultMessage: "Back"
                    })
                  }
                )
              }
            ),
            /* @__PURE__ */ jsxs(ContentLayout, { children: [
              user?.registrationToken && /* @__PURE__ */ jsx(Box, { paddingBottom: 6, children: /* @__PURE__ */ jsx(MagicLink, { registrationToken: user.registrationToken }) }),
              /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 7, children: [
                /* @__PURE__ */ jsx(
                  Box,
                  {
                    background: "neutral0",
                    hasRadius: true,
                    shadow: "filterShadow",
                    paddingTop: 6,
                    paddingBottom: 6,
                    paddingLeft: 7,
                    paddingRight: 7,
                    children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
                      /* @__PURE__ */ jsx(Typography, { variant: "delta", as: "h2", children: formatMessage({
                        id: "app.components.Users.ModalCreateBody.block-title.details",
                        defaultMessage: "Details"
                      }) }),
                      /* @__PURE__ */ jsx(Grid, { gap: 5, children: layout.map((row) => {
                        return row.map((input) => {
                          return /* @__PURE__ */ jsx(GridItem, { ...input.size, children: /* @__PURE__ */ jsx(
                            GenericInput,
                            {
                              ...input,
                              disabled: !canUpdate,
                              error: errors[input.name],
                              onChange: handleChange,
                              value: values[input.name] || ""
                            }
                          ) }, input.name);
                        });
                      }) })
                    ] })
                  }
                ),
                /* @__PURE__ */ jsx(
                  Box,
                  {
                    background: "neutral0",
                    hasRadius: true,
                    shadow: "filterShadow",
                    paddingTop: 6,
                    paddingBottom: 6,
                    paddingLeft: 7,
                    paddingRight: 7,
                    children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
                      /* @__PURE__ */ jsx(Typography, { variant: "delta", as: "h2", children: formatMessage({
                        id: "global.roles",
                        defaultMessage: "User's role"
                      }) }),
                      /* @__PURE__ */ jsx(Grid, { gap: 5, children: /* @__PURE__ */ jsx(GridItem, { col: 6, xs: 12, children: /* @__PURE__ */ jsx(
                        SelectRoles,
                        {
                          disabled: !canUpdate,
                          error: errors.roles,
                          onChange: handleChange,
                          value: values.roles
                        }
                      ) }) })
                    ] })
                  }
                )
              ] })
            ] })
          ] });
        }
      }
    )
  ] });
};
EditPage.propTypes = {
  canUpdate: PropTypes.bool.isRequired
};
const ProtectedEditPage = () => {
  const toggleNotification = useNotification();
  const permissions = useSelector(selectAdminPermissions);
  const memoizedPermissions = React__default.useMemo(
    () => ({
      read: permissions.settings.users.read,
      update: permissions.settings.users.update
    }),
    [permissions.settings.users]
  );
  const {
    isLoading,
    allowedActions: { canRead, canUpdate }
  } = useRBAC(memoizedPermissions);
  const { state } = useLocation();
  const from = state?.from ?? "/";
  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__ */ jsx(LoadingIndicatorPage, {});
  }
  if (!canRead && !canUpdate) {
    return /* @__PURE__ */ jsx(Redirect, { to: from });
  }
  return /* @__PURE__ */ jsx(EditPage, { canUpdate });
};
export {
  ProtectedEditPage as default
};
//# sourceMappingURL=index-96576e39.mjs.map
