import { r as reactExports, j as jsxRuntimeExports } from "./vendor-react-DYNCg6N5.js";
import { u as useStyles, v as validateCreateRolesSchema } from "./index-C2HWmCvh.js";
import { A as AddButton } from "./index-72JBTuLT.js";
import { S as SelectWithPagination } from "./index-CfN7Ll0p.js";
import { S as SelectUserModal } from "./index-DFEP7Sv_.js";
import { S as SelectGroupSimpleModal } from "./index-BWhdniX1.js";
import { a8 as useAddRolesMutation } from "./index-DfebxkL9.js";
import { B as Badges } from "./index-woYEqWvh.js";
import { S as SelectGroupModal, a as transformObjectIfKeyIsNull } from "./index-Ds4Bnwmy.js";
import { g as getValidateErrors } from "./validation-Ds00Zghx.js";
import { S as SelectQuotas } from "./index-BoQKW1g7.js";
import { u as useTranslation } from "./vendor-i18n-wisIXUFi.js";
import { z as useForm, b as Box, a0 as SimpleGrid, E as TextInput, T as Text, F as Flex, B as Button, U as UnstyledButton, V as LoadingOverlay, s as showNotification } from "./vendor-mantine-h0WlM2Mj.js";
const RolesCreateForm = ({
  close,
  onSuccess
}) => {
  var _a;
  const {
    classes
  } = useStyles();
  const {
    t
  } = useTranslation();
  const [isUserModalOpen, setIsUserModalOpen] = reactExports.useState(false);
  const [isRoleModalOpen, setIsRoleModalOpen] = reactExports.useState(false);
  const [isAllowedRoleModalOpen, setIsAllowedRoleModalOpen] = reactExports.useState(false);
  const [selectedUser, setSelectedUser] = reactExports.useState(null);
  const [selectedRoles, setSelectedRoles] = reactExports.useState(null);
  const [selectedAllowedRoles, setSelectedAllowedRoles] = reactExports.useState({});
  const [createRoles, {
    isLoading
  }] = useAddRolesMutation();
  const closeModals = () => {
    setIsUserModalOpen(false);
    setIsRoleModalOpen(false);
    setIsAllowedRoleModalOpen(false);
  };
  const handleConfirmSelectUserModal = async () => {
    if (!selectedUser) {
      return;
    }
    form.setFieldValue("Owner.Id", (selectedUser == null ? void 0 : selectedUser.Id) ?? null);
    form.setFieldValue("Owner.Name", (selectedUser == null ? void 0 : selectedUser.Name) ?? null);
    closeModals();
  };
  const handleCloseSelectUserModal = () => {
    setIsUserModalOpen(false);
  };
  const handleCloseAllowedRoleModal = () => {
    setIsAllowedRoleModalOpen(false);
  };
  const handleRemoveRoles = () => {
    setSelectedRoles(null);
    form.setFieldValue("Parent.Id", null);
  };
  const handleRemoveAllowedRole = (item) => {
    const index = form.values.AllowedRoles.findIndex((i) => i.Id === item.Id);
    form.removeListItem("AllowedRoles", index);
  };
  const handleRemoveUser = () => {
    setSelectedUser(null);
    form.setFieldValue("Owner.Id", null);
    form.setFieldValue("Owner.Name", null);
  };
  const handleRemoveSelfViewAccess = () => {
    form.setFieldValue("HasSelfViewAccess", false);
  };
  const setGroupId = async (id) => {
    form.setFieldValue("Parent.Id", id);
    closeModals();
  };
  const setGroup = async (group) => {
    setSelectedRoles(group);
  };
  const handleAddAllowedRoles = (roles) => {
    roles.forEach((role) => {
      form.insertListItem("AllowedRoles", role);
    });
    setIsAllowedRoleModalOpen(false);
  };
  const form = useForm({
    initialValues: {
      Name: "",
      Customer: {
        Id: null,
        Name: null
      },
      Parent: {
        Id: null
      },
      Owner: {
        Id: null,
        Name: null
      },
      Quota: {
        Id: null,
        Name: ""
      },
      AllowedRoles: [],
      HasSelfViewAccess: true
      //Type: 0,
    },
    validateInputOnChange: true,
    validate: (values) => getValidateErrors(validateCreateRolesSchema(t), values)
  });
  const isDisabled = Object.keys(form.errors).length !== 0 || !form.isDirty();
  const handleSubmit = async (values_0) => {
    var _a2;
    const formatted = transformObjectIfKeyIsNull(JSON.parse(JSON.stringify(values_0)));
    try {
      const res = await createRoles(formatted);
      if (!Object.keys(res).includes("error")) {
        showNotification({
          title: t("roles.roleAdded"),
          message: "",
          autoClose: true,
          color: "green"
        });
        onSuccess && onSuccess();
        handleClose();
      } else {
        showNotification({
          title: `${(_a2 = res == null ? void 0 : res.error) == null ? void 0 : _a2.data}`,
          message: "",
          autoClose: true,
          color: "red"
        });
      }
    } catch (err) {
      console.warn("Create roles ERROR", err);
    }
  };
  const handleClose = () => {
    close();
    form.reset();
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { className: classes.modalRoot, onSubmit: form.onSubmit(handleSubmit), children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { className: classes.modalContainer, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(SimpleGrid, { cols: 1, w: "100%", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(TextInput, { withAsterisk: true, label: t("roles.name"), placeholder: "", ...form.getInputProps("Name") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SelectWithPagination, { form, fieldName: "Customer.Id", label: t("roles.addFilial"), placeholder: t("choose"), defaultValue: form.getInputProps("Customer.Id").value || null, value: form.getInputProps("Customer.Id").value, isRoleComponent: true, filialName: form.getInputProps("Customer.Name").value, customerField: "Customer.Name" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SelectQuotas, { form, fieldName: "Quota.Id", quotaField: "Quota.Name", Customer: form.getInputProps("Customer.Id").value, value: form.values.Quota.Id, QuotaName: form.values.Quota.Name }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(SimpleGrid, { cols: 1, spacing: "xs", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Text, { size: "sm", fw: "500", children: t("roles.whoCanShareAccess") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(AddButton, { className: classes.addButton, onClick: () => setIsAllowedRoleModalOpen(true), children: t("roles.addAllowedRoles") }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Flex, { gap: "xs", wrap: "wrap", children: [
            form.values.HasSelfViewAccess && form.values.Name && /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Badges, { label: form.values.Name, onRemove: () => handleRemoveSelfViewAccess }) }),
            form.values.AllowedRoles && ((_a = form.values.AllowedRoles) == null ? void 0 : _a.map((item_0) => /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Badges, { label: item_0.Name, onRemove: () => handleRemoveAllowedRole(item_0) }) }, item_0.Id)))
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(SimpleGrid, { cols: 1, spacing: "xs", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(AddButton, { className: classes.addButton, onClick: () => setIsRoleModalOpen(true), children: t("roles.addParentRole") }),
          selectedRoles && /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Badges, { label: selectedRoles == null ? void 0 : selectedRoles.label, onRemove: handleRemoveRoles }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(SimpleGrid, { cols: 1, spacing: "xs", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(AddButton, { className: classes.addButton, onClick: () => setIsUserModalOpen(true), children: t("roles.addRoleManager") }),
          form.values.Owner.Name && /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Badges, { label: form.values.Owner.Name, onRemove: handleRemoveUser }) })
        ] })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { className: classes.modalFooter, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { type: "submit", size: "sm", radius: 8, w: "49%", disabled: isDisabled, children: t("create") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(UnstyledButton, { type: "button", ml: 8, className: classes.modalCancelBtn, w: "49%", onClick: close, children: t("cancel") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(SelectGroupSimpleModal, { onClose: closeModals, isOpened: isRoleModalOpen, title: t("roles.addParentRole"), setGroupId, setGroup }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(SelectGroupModal, { isOpened: isAllowedRoleModalOpen, title: t("profile.addRole"), onClose: handleCloseAllowedRoleModal, setSelectedGroup: setSelectedAllowedRoles, selectedGroup: selectedAllowedRoles, setGroups: handleAddAllowedRoles, groups: form.values.AllowedRoles }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(SelectUserModal, { multipleUsers: false, isOpened: isUserModalOpen, title: t("roles.addRoleManager"), onClose: closeModals, setSelectedUsers: setSelectedUser, userId: selectedUser == null ? void 0 : selectedUser.Id, controlSection: true, controlSectionProps: {
        confirmProps: {
          btnName: t("add"),
          fn: handleConfirmSelectUserModal
        },
        cancelProps: {
          btnName: t("cancel"),
          fn: handleCloseSelectUserModal
        }
      } })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(LoadingOverlay, { visible: isLoading })
  ] });
};
export {
  RolesCreateForm as R
};
//# sourceMappingURL=form-BjvLuBG-.js.map
