import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import { useMemo, Fragment } from 'react';
import { useFormikContext } from 'formik';
import { findById, hyphenate, isNotEmpty } from '@bigbinary/neeto-cist';
import { SINGULAR } from '@bigbinary/neeto-commons-frontend/constants';
import Typography from '@bigbinary/neetoui/Typography';
import Checkbox from '@bigbinary/neetoui/Checkbox';
import Tooltip from '@bigbinary/neetoui/Tooltip';
import { prop, concat, append, equals, groupBy, pluck } from 'ramda';
import { useTranslation } from 'react-i18next';
import { n } from './inject-css-C2dztUxs.js';
import { jsxs, jsx } from 'react/jsx-runtime';

var css = ".ntm-roles-pane__body{margin-bottom:1.5rem;width:100%}.ntm-roles-pane__body-wrapper>*+*{margin-top:1rem}.ntm-roles-pane__body>*+*{margin-top:1.5rem}.ntm-roles-pane__footer{display:flex;gap:.5rem}.ntm-roles-permission__heading{padding-top:.5rem}.ntm-roles-permission__card{background-color:rgb(var(--neeto-ui-white));display:flex;flex-direction:column;gap:.75rem;padding:.4rem 0;position:relative}.ntm-roles-permission__card:after{background-color:rgb(var(--neeto-ui-gray-300));content:\"\";height:1px;inset-inline-start:-.9375rem;position:absolute;top:.875rem;width:.625rem}.ntm-roles-permission__card--description{flex-grow:1}.ntm-roles-permission__card--checkbox{padding:0 .5rem}.ntm-roles-permission__card .neeto-ui-checkbox__wrapper .neeto-ui-checkbox__container{align-items:flex-start}.ntm-roles-permission__card .neeto-ui-checkbox__wrapper .neeto-ui-checkbox__container .neeto-ui-checkbox[type=checkbox]:disabled+.neeto-ui-label{cursor:not-allowed;opacity:.5}.ntm-roles-permission__sub-blocks{position:relative}.ntm-roles-permission__sub-blocks:before{background-color:rgb(var(--neeto-ui-gray-300));content:\"\";height:calc(100% - .875rem);inset-inline-start:.5rem;position:absolute;top:0;width:.0625rem}.ntm-roles-permission__sub-blocks:empty{display:none}.ntm-roles-permission-category-card{border:1px solid rgb(var(--neeto-ui-gray-200));border-radius:var(--neeto-ui-rounded);padding:.625rem 1.25rem;transition:all .3s}.ntm-roles-permission-category-card--active{background-color:rgba(var(--neeto-ui-primary-50),1);border-color:rgb(var(--neeto-ui-primary-500));outline:1px solid rgb(var(--neeto-ui-primary-500))}.ntm-roles-permission-category-card--active .ntm-roles-permission__card{background-color:transparent}.ntm-roles-permission-category-card>.ntm-roles-permission__card:after{display:none}.ntm-roles-permission__card>.neeto-ui-checkbox__wrapper .neeto-ui-label{font-weight:400}.ntm-roles-permission-category-card>.ntm-roles-permission__card>.neeto-ui-checkbox__wrapper .neeto-ui-label{font-size:.9375rem}@keyframes ntm-roles-permission-blink{0%,to{color:inherit}50%{color:rgb(var(--neeto-ui-primary-500));font-weight:700}}.ntm-roles-permission__card--blink>.neeto-ui-checkbox__wrapper .neeto-ui-label{animation:ntm-roles-permission-blink .6s ease-in-out 0s 3}\n/*# sourceMappingURL=data:application/json;base64,  */";
n(css,{});

function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var sortPermissionsBySequence = function sortPermissionsBySequence() {
  var _permissions$;
  var permissions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  return permissions !== null && permissions !== void 0 && (_permissions$ = permissions[0]) !== null && _permissions$ !== void 0 && _permissions$.sequence ? permissions.sort(function (first, second) {
    return first.sequence - second.sequence;
  }) : permissions;
};
var getPermissionGroups = function getPermissionGroups() {
  var permissions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var sortBySequence = sortPermissionsBySequence(permissions);
  var groupedPermissions = new Map();
  sortBySequence.forEach(function (permission) {
    if (groupedPermissions.has(permission === null || permission === void 0 ? void 0 : permission.category)) {
      var category = groupedPermissions.get(permission.category);
      var currentPermissions = category.get("permissions");
      var _permissions = append(permission, currentPermissions);
      category.set("permissions", _permissions);
    } else {
      var value = new Map();
      value.set("permissions", append(permission, []));
      value.set("isPermissionVisible", true);
      groupedPermissions.set(permission === null || permission === void 0 ? void 0 : permission.category, value);
    }
  });
  return groupedPermissions;
};
var getModifiedPermissions = function getModifiedPermissions() {
  var roles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var modifiedRoles = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  return modifiedRoles.map(function (role) {
    var oldPermissions = findById(role.id, roles).permissionIds;
    if (equals(oldPermissions, role.permissionIds)) return false;
    return {
      id: role.id,
      permissionIds: role.permissionIds
    };
  }).filter(Boolean);
};
var _attachChildrenRecursively = function attachChildrenRecursively(permission, permissionsNameMap, permissionRelationConfig) {
  var _ref = permissionRelationConfig[permission.name] || {},
    children = _ref.children;
  return children ? _objectSpread$1(_objectSpread$1({}, permission), {}, {
    children: children.flatMap(function (childName) {
      var _permissionsNameMap$c;
      var childPermission = (_permissionsNameMap$c = permissionsNameMap[childName]) === null || _permissionsNameMap$c === void 0 ? void 0 : _permissionsNameMap$c[0];
      if (!childPermission) return [];
      return _attachChildrenRecursively(childPermission, permissionsNameMap, permissionRelationConfig);
    })
  }) : permission;
};
var _findChildIdsRecursively = function findChildIdsRecursively(permission, permissionsNameMap, permissionRelationConfig) {
  var _ref2 = permissionRelationConfig[permission.name] || {},
    children = _ref2.children;
  return children ? concat(children.flatMap(function (childName) {
    var _permissionsNameMap$c2;
    var childPermission = (_permissionsNameMap$c2 = permissionsNameMap[childName]) === null || _permissionsNameMap$c2 === void 0 ? void 0 : _permissionsNameMap$c2[0];
    if (!childPermission) return [];
    return _findChildIdsRecursively(childPermission, permissionsNameMap, permissionRelationConfig);
  }), [permission.id]) : [permission.id];
};
var getChildrenRemovedFromRoot = function getChildrenRemovedFromRoot(_ref3) {
  var permissions = _ref3.permissions,
    permissionsNameMap = _ref3.permissionsNameMap,
    permissionRelationConfig = _ref3.permissionRelationConfig;
  var permissionsWithChildren = permissions.map(function (permission) {
    return _attachChildrenRecursively(permission, permissionsNameMap, permissionRelationConfig);
  });
  var childPermissions = Object.values(permissionRelationConfig).flatMap(prop("children"));
  return permissionsWithChildren.filter(function (permission) {
    return !childPermissions.includes(permission.name);
  });
};

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var Permissions = function Permissions(_ref) {
  var _ref$permissions = _ref.permissions,
    permissions = _ref$permissions === void 0 ? [] : _ref$permissions,
    _ref$isDisabled = _ref.isDisabled,
    isDisabled = _ref$isDisabled === void 0 ? false : _ref$isDisabled,
    _ref$permissionRelati = _ref.permissionRelationConfig,
    permissionRelationConfig = _ref$permissionRelati === void 0 ? {} : _ref$permissionRelati;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var _useFormikContext = useFormikContext(),
    setFieldValue = _useFormikContext.setFieldValue,
    values = _useFormikContext.values;
  var _values$permissionIds = values.permissionIds,
    permissionIds = _values$permissionIds === void 0 ? [] : _values$permissionIds;
  var permissionsNameMap = groupBy(prop("name"))(permissions);
  var handleTogglePermission = function handleTogglePermission(permissionId) {
    var permission = findById(permissionId, permissions);
    var nextPermissionIds = [];
    if (permissionIds.includes(permissionId)) {
      var childIds = [];
      if (permissionRelationConfig[permission.name]) {
        childIds = _findChildIdsRecursively(permission, permissionsNameMap, permissionRelationConfig);
      }
      var permissionIdsToBeUnchecked = [permissionId].concat(_toConsumableArray(childIds));
      nextPermissionIds = permissionIds.filter(function (id) {
        return !permissionIdsToBeUnchecked.includes(id);
      });
    } else {
      var _uncheckOnSelect$flat;
      var _ref2 = permissionRelationConfig[permission.name] || {},
        uncheckOnSelect = _ref2.uncheckOnSelect;
      var uncheckOnSelectPermissions = (_uncheckOnSelect$flat = uncheckOnSelect === null || uncheckOnSelect === void 0 ? void 0 : uncheckOnSelect.flatMap(function (name) {
        return permissionsNameMap[name];
      })) !== null && _uncheckOnSelect$flat !== void 0 ? _uncheckOnSelect$flat : [];
      var _childIds = uncheckOnSelectPermissions.flatMap(function (permission) {
        return _findChildIdsRecursively(permission, permissionsNameMap, permissionRelationConfig);
      });
      var uncheckedPermissionIds = pluck("id", uncheckOnSelectPermissions);
      var _permissionIdsToBeUnchecked = [].concat(_toConsumableArray(uncheckedPermissionIds), _toConsumableArray(_childIds));
      nextPermissionIds = uncheckOnSelect ? [].concat(_toConsumableArray(permissionIds.filter(function (id) {
        return !_permissionIdsToBeUnchecked.includes(id);
      })), [permissionId]) : [].concat(_toConsumableArray(permissionIds), [permissionId]);
    }
    setFieldValue("permissionIds", nextPermissionIds.sort());
  };
  var groupedPermissions = useMemo(function () {
    var childrenRemovedFromRoot = getChildrenRemovedFromRoot({
      permissions: permissions,
      permissionsNameMap: permissionsNameMap,
      permissionRelationConfig: permissionRelationConfig
    });
    return groupBy(prop("category"))(childrenRemovedFromRoot);
  }, [permissions]); // eslint-disable-line react-hooks/exhaustive-deps

  var _renderPermission = function renderPermission(_ref3) {
    var _permissionRelationCo;
    var id = _ref3.id,
      name = _ref3.name,
      description = _ref3.description,
      children = _ref3.children,
      _ref3$isParentChecked = _ref3.isParentChecked,
      isParentChecked = _ref3$isParentChecked === void 0 ? true : _ref3$isParentChecked,
      _ref3$index = _ref3.index,
      index = _ref3$index === void 0 ? 1 : _ref3$index;
    var sortedChildren = children && sortPermissionsBySequence(children);
    var isCheckingDisabled = !isParentChecked || isDisabled;
    var isChecked = permissionIds.includes(id);
    var permissionsToBeUnchecked = (_permissionRelationCo = permissionRelationConfig[name]) === null || _permissionRelationCo === void 0 ? void 0 : _permissionRelationCo.uncheckOnSelect;
    var hasUnCheckOnSelect = permissionsToBeUnchecked && isNotEmpty(permissionsToBeUnchecked);
    var tooltipMessage = hasUnCheckOnSelect && t("neetoTeamMembers.tooltips.uncheckOnSelectPermissions", {
      permissions: permissionsToBeUnchecked.flatMap(function (name) {
        return pluck("description", permissionsNameMap[name]);
      }).join(", ")
    });
    return /*#__PURE__*/jsx(Fragment, {
      children: /*#__PURE__*/jsx(Tooltip, {
        content: tooltipMessage,
        disabled: !tooltipMessage || isChecked,
        position: "left-start",
        children: /*#__PURE__*/jsxs("div", {
          className: "ntm-roles-permission__card",
          "data-testid": "ntm-roles-permission-sub-category-card-".concat(index),
          id: "ntm-role-permission-".concat(id),
          children: [/*#__PURE__*/jsx(Checkbox, {
            checked: isChecked,
            className: "grow-0",
            "data-testid": "ntm-roles-permission-checkbox",
            disabled: isCheckingDisabled,
            label: description,
            onChange: function onChange() {
              return handleTogglePermission(id);
            }
          }), /*#__PURE__*/jsx("div", {
            className: "ntm-roles-permission__sub-blocks neeto-ui-relative neeto-ui-pl-6",
            children: sortedChildren === null || sortedChildren === void 0 ? void 0 : sortedChildren.map(function (childPermission) {
              return _renderPermission(_objectSpread(_objectSpread({}, childPermission), {}, {
                isParentChecked: isChecked,
                index: index + 1
              }));
            })
          })]
        })
      })
    }, id);
  };
  return /*#__PURE__*/jsxs("div", {
    className: "ntm-roles-pane__body-wrapper",
    children: [/*#__PURE__*/jsxs("div", {
      children: [/*#__PURE__*/jsx(Typography, {
        lineHeight: "normal",
        style: "h3",
        weight: "semibold",
        children: t("neetoTeamMembers.common.permission", SINGULAR)
      }), /*#__PURE__*/jsx(Typography, {
        lineHeight: "normal",
        style: "body2",
        children: t("neetoTeamMembers.helpers.configPermissions")
      })]
    }), Object.keys(groupedPermissions).map(function (category) {
      return /*#__PURE__*/jsxs("div", {
        className: "ntm-roles-permission",
        "data-testid": "ntm-roles-permission-card",
        id: "ntm-role-permission-category-".concat(hyphenate(category)),
        children: [/*#__PURE__*/jsx(Typography, {
          className: "ntm-roles-permission__heading neeto-ui-mb-2",
          "data-testid": "ntm-roles-permission-category-title",
          lineHeight: "normal",
          style: "h4",
          weight: "semibold",
          children: category
        }), /*#__PURE__*/jsx("div", {
          className: "ntm-roles-permission-category-card",
          children: groupedPermissions[category].map(_renderPermission)
        })]
      }, category);
    })]
  });
};

export { Permissions as P, getPermissionGroups as a, getModifiedPermissions as b, getChildrenRemovedFromRoot as g, sortPermissionsBySequence as s };
//# sourceMappingURL=Permissions-BCkBjBNL.js.map
