import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import { useMemo, Fragment } from 'react';
import { Typography, Tooltip, Checkbox, Label, cn } from '@bigbinary/neeto-atoms';
import { useFormikContext } from 'formik';
import { findById, hyphenate, isNotEmpty } from '@bigbinary/neeto-cist';
import { SINGULAR } from '@bigbinary/neeto-commons-frontend/v2/constants';
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:var(--background);display:flex;flex-direction:column;gap:.75rem;padding:.4rem 0;position:relative}.ntm-roles-permission__card:after{background-color:var(--border);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__sub-blocks{position:relative}.ntm-roles-permission__sub-blocks:before{background-color:var(--border);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 var(--border);border-radius:.375rem;border-radius:var(--radius,.375rem);padding:.625rem 1.25rem;transition:all .3s}.ntm-roles-permission-category-card--active{border-color:var(--primary);outline:1px solid var(--primary)}.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}@keyframes ntm-roles-permission-blink{0%,to{color:inherit}50%{color:var(--primary);font-weight:700}}.ntm-roles-permission__card--blink label{animation:ntm-roles-permission-blink .6s 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S1yb2xlcy1wZXJtaXNzaW9uLWNhdGVnb3J5LWNhcmQ+Lm50bS1yb2xlcy1wZXJtaXNzaW9uX19jYXJkOjphZnRlciB7XG4gIGRpc3BsYXk6IG5vbmU7XG59XG5cbkBrZXlmcmFtZXMgbnRtLXJvbGVzLXBlcm1pc3Npb24tYmxpbmsge1xuXG4gIDAlLFxuICAxMDAlIHtcbiAgICBjb2xvcjogaW5oZXJpdDtcbiAgfVxuXG4gIDUwJSB7XG4gICAgY29sb3I6IHZhcigtLXByaW1hcnkpO1xuICAgIGZvbnQtd2VpZ2h0OiBib2xkO1xuICB9XG59XG5cbi5udG0tcm9sZXMtcGVybWlzc2lvbl9fY2FyZC0tYmxpbmsgbGFiZWwge1xuICBhbmltYXRpb246IG50bS1yb2xlcy1wZXJtaXNzaW9uLWJsaW5rIDYwMG1zIGVhc2UtaW4tb3V0IDBzIDM7XG59Il19 */";
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 ? _toConsumableArray(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 && !isChecked ? tooltipMessage : null,
        position: "left",
        children: /*#__PURE__*/jsxs("div", {
          className: "ntm-roles-permission__card relative flex flex-col gap-3 bg-background py-1.5",
          "data-testid": "ntm-roles-permission-sub-category-card-".concat(index),
          id: "ntm-role-permission-".concat(id),
          children: [/*#__PURE__*/jsxs("div", {
            className: "flex items-start gap-2",
            children: [/*#__PURE__*/jsx(Checkbox, {
              checked: isChecked,
              className: "mt-0.5 shrink-0",
              "data-testid": "ntm-roles-permission-checkbox",
              disabled: isCheckingDisabled,
              id: "permission-".concat(id),
              onCheckedChange: function onCheckedChange() {
                return handleTogglePermission(id);
              }
            }), /*#__PURE__*/jsx(Label, {
              htmlFor: "permission-".concat(id),
              className: cn("font-normal leading-relaxed", isCheckingDisabled ? "cursor-not-allowed opacity-50" : "cursor-pointer"),
              children: description
            })]
          }), /*#__PURE__*/jsx("div", {
            className: "ntm-roles-permission__sub-blocks relative 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: "space-y-4",
    children: [/*#__PURE__*/jsxs("div", {
      children: [/*#__PURE__*/jsx(Typography, {
        variant: "body1",
        weight: "semibold",
        children: t("neetoTeamMembers.common.permission", SINGULAR)
      }), /*#__PURE__*/jsx(Typography, {
        color: "muted",
        variant: "body3",
        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: "mb-2 pt-2",
          "data-testid": "ntm-roles-permission-category-title",
          variant: "body3",
          weight: "semibold",
          children: category
        }), /*#__PURE__*/jsx("div", {
          className: "ntm-roles-permission-category-card neeto-ui-rounded-md border border-border p-2.5 px-5 transition-all duration-300",
          children: groupedPermissions[category].map(_renderPermission)
        })]
      }, category);
    })]
  });
};

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