import { jsx as n, Fragment as Oe, jsxs as f } from "react/jsx-runtime";
import { debounce as mt, Typography as U, Box as le, TextField as Pe, ListItem as ke, FormControlLabel as De, Checkbox as Ce, Tooltip as Je, Modal as Ae, Card as Le, IconButton as ve, Button as he, Autocomplete as ft, Menu as pt, MenuItem as ht } from "@mui/material";
import b from "@mui/material/Grid2";
import i from "prop-types";
import vt from "@/views/custom-components/CustomConfirmationModal";
import { useRef as _e, useState as p, useEffect as te, useCallback as gt, createElement as je } from "react";
import { useTheme as yt } from "@mui/material/styles";
import { o as K, u as fe, a as xt, i as wt, g as Nt } from "./Features-Cshdl06N-CZ02Tt89.js";
import { getRoleList as bt, execute as Z } from "@/common/services/GlobalApis.js";
import "@/assets/scss/scrollBar.scss";
import { useForm as ge, Controller as It } from "react-hook-form";
import { showToast as C } from "@/common/toaster/toaster";
import St from "@/hooks/useTrackEvent";
import { useTranslateProvider as ze } from "@/common/languageTranslator/TranslationContext";
import { FontAwesomeIcon as z } from "@fortawesome/react-fontawesome";
import { faTrash as Ot, faPen as kt, faAngleDown as Dt, faEyeSlash as Te, faEye as Ee, faXmark as Be, faCheck as Ct, faArrowRight as Jt } from "@fortawesome/free-solid-svg-icons";
import { yupResolver as _t } from "@hookform/resolvers/yup";
import * as X from "yup";
import pe from "@/views/custom-components/CustomCheckBox";
import Me from "@/views/custom-components/CustomDatePicker";
import { execute as jt } from "@/common/services/GlobalApis";
import Tt from "@/views/custom-components/CustomAutoComplete";
import Et from "@mui/material/Accordion";
import Mt from "@mui/material/AccordionDetails";
import Pt from "@mui/material/AccordionSummary";
import { useSelector as At } from "react-redux";
import { getUseSkeleton as Lt } from "@/store/reducers/SkeletonReducer";
const zt = X.object().shape({
  noStartDate: X.boolean().default(!0),
  noEndDate: X.boolean().default(!0),
  startDate: X.date().nullable().when("noStartDate", {
    is: !1,
    then: (s) => s.required("Start date is required")
  }),
  endDate: X.date().nullable().when("noEndDate", {
    is: !1,
    then: (s) => s.required("End date is required")
  }).test(
    "endAfterStart",
    "End date must be after start date",
    function(s) {
      const { startDate: J, noEndDate: g } = this.parent;
      return !s || g || !J ? !0 : new Date(s) >= new Date(J);
    }
  ),
  isBackendOnly: X.boolean().default(!1)
});
function Fe({
  isOpen: s,
  onClose: J,
  pendingGrant: g,
  subMenuId: S,
  newApiData: _
}) {
  const { translate: j } = ze(), {
    handleSubmit: E,
    control: O,
    reset: I,
    watch: d,
    formState: { errors: h },
    trigger: A
  } = ge({
    resolver: _t(zt),
    defaultValues: {
      noStartDate: !0,
      noEndDate: !0,
      startDate: null,
      endDate: null,
      isBackendOnly: !1
    },
    mode: "onChange"
  }), k = d("noStartDate"), B = d("noEndDate"), L = d("startDate"), y = d("endDate"), D = async (x) => {
    var c, N;
    if (g) {
      try {
        await Z({
          code: "grant_permission",
          parameters: {
            featureName: g.id,
            roleIds: g != null && g.designationId ? String(g == null ? void 0 : g.designationId) : null,
            userIds: g != null && g.userId ? String(g.userId) : null,
            startDate: x.noStartDate ? null : x.startDate,
            endDate: x.noEndDate ? null : x.endDate,
            isBackendOnly: x.isBackendOnly
          }
        }), C({
          type: "success",
          message: "Permission Granted Successfully"
        });
        const { data: T } = await K(S);
        _(T);
      } catch (T) {
        C({
          type: "error",
          message: `Error granting permission: ${(N = (c = T == null ? void 0 : T.response) == null ? void 0 : c.data) == null ? void 0 : N.message}`
        });
      }
      I(), J();
    }
  }, M = () => {
    I(), J();
  };
  return /* @__PURE__ */ n(Ae, { open: s, onClose: M, children: /* @__PURE__ */ n(le, { className: "fixed inset-0 flex items-start justify-center z-50 overflow-y-auto bg-opacity-10", children: /* @__PURE__ */ n(
    Le,
    {
      className: `
          relative mt-10 p-4 shadow-lg flex flex-col rounded-xl
          w-[95vw] max-w-md
          sm:w-[80vw] sm:max-w-lg
          md:w-[60vw] md:max-w-xl
          lg:w-[40vw] lg:max-w-2xl
          xl:w-[30vw] xl:max-w-3xl
        `,
      children: /* @__PURE__ */ f("form", { onSubmit: E(D), children: [
        /* @__PURE__ */ f(b, { className: "flex justify-between items-center mb-4", children: [
          /* @__PURE__ */ n(
            U,
            {
              variant: "h6",
              className: "text-base sm:text-lg text-customBlue",
              children: j("Set Access Window")
            }
          ),
          /* @__PURE__ */ n(ve, { onClick: M, children: /* @__PURE__ */ n(z, { icon: Be }) })
        ] }),
        /* @__PURE__ */ f(b, { className: "flex flex-col sm:flex-row gap-4 mb-4", children: [
          /* @__PURE__ */ f(b, { className: "flex-1", children: [
            /* @__PURE__ */ n(
              pe,
              {
                defaultChecked: !0,
                label: "No Start Date",
                control: O,
                errors: h,
                name: "noStartDate",
                onChange: () => A("startDate")
              }
            ),
            /* @__PURE__ */ n(
              Me,
              {
                control: O,
                name: "startDate",
                errors: h,
                disabled: k,
                format: "DD/MM/YYYY",
                maxDate: y || void 0
              }
            )
          ] }),
          /* @__PURE__ */ f(b, { className: "flex-1", children: [
            /* @__PURE__ */ n(
              pe,
              {
                label: "No End Date",
                control: O,
                name: "noEndDate",
                errors: h,
                onChange: () => A("endDate")
              }
            ),
            /* @__PURE__ */ n(
              Me,
              {
                control: O,
                name: "endDate",
                errors: h,
                disabled: B,
                format: "DD/MM/YYYY",
                minDate: L || void 0
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ n(
          pe,
          {
            label: "Is Backend Only?",
            control: O,
            name: "isBackendOnly",
            className: ""
          }
        ),
        /* @__PURE__ */ f(b, { className: "flex justify-end gap-3 mt-2", children: [
          /* @__PURE__ */ n(
            he,
            {
              variant: "contained",
              color: "secondary",
              size: "small",
              onClick: M,
              type: "button",
              className: "mt-2",
              children: j("Close")
            }
          ),
          /* @__PURE__ */ n(
            he,
            {
              variant: "contained",
              color: "primary",
              size: "small",
              type: "submit",
              className: "mt-2",
              children: j("Submit")
            }
          )
        ] })
      ] })
    }
  ) }) });
}
Fe.propTypes = {
  isOpen: i.bool,
  onClose: i.func,
  pendingGrant: i.object,
  execute: i.func,
  getFeatureDataV2: i.func,
  subMenuId: i.string,
  newApiData: i.func,
  showToast: i.func
};
function Re({
  translate: s,
  onSubmit: J,
  roleList: g,
  featureData: S
}) {
  const [_, j] = p(""), [E, O] = p(""), [I, d] = p([]), { control: h, handleSubmit: A, reset: k } = ge({}), B = g.filter(
    (y) => !(S != null && S.some((D) => (D == null ? void 0 : D.designationId) === (y == null ? void 0 : y.id)))
  );
  te(() => {
    const y = setTimeout(() => {
      O(_);
    }, 300);
    return () => clearTimeout(y);
  }, [_]), te(() => {
    E !== "" && L(E);
  }, [E]), te(() => {
    L("");
  }, []);
  const L = async (y, D = S) => {
    try {
      const { data: M } = await jt({
        code: "user_search_for_selectize",
        parameters: {
          searchString: y
        }
      }), x = ((M == null ? void 0 : M.result) || []).filter((c) => c == null ? void 0 : c.id).filter(
        (c) => !(D != null && D.some((N) => (N == null ? void 0 : N.userId) === (c == null ? void 0 : c.id)))
      ).map((c) => ({
        ...c,
        displayName: `${c.firstName || ""} ${c.lastName || ""} (${c.userName || ""})`.trim()
      }));
      d(x);
    } catch (M) {
      console.error(M);
    }
  };
  return /* @__PURE__ */ f(b, { className: "flex flex-col md:flex-row gap-3 md:pl-5 justify-start w-full", children: [
    /* @__PURE__ */ f(
      b,
      {
        className: "flex flex-col md:flex-row md:space-x-5 justify-center items-center w-full",
        children: [
          /* @__PURE__ */ f(b, { className: "flex flex-row flex-2 md:space-x-3 items-center w-full", children: [
            /* @__PURE__ */ n(U, { className: "flex-1", children: s("User") }),
            /* @__PURE__ */ n(b, { className: "flex-3", children: /* @__PURE__ */ n(
              It,
              {
                name: "roles",
                id: "roles",
                users: !0,
                control: h,
                defaultValue: null,
                render: ({ field: { onChange: y, value: D, ref: M } }) => /* @__PURE__ */ n(
                  ft,
                  {
                    options: I,
                    getOptionLabel: (x) => x.displayName || "",
                    isOptionEqualToValue: (x, c) => x.id === (c == null ? void 0 : c.id),
                    value: D || null,
                    onChange: (x, c, N) => {
                      N === "clear" && L(""), y(c);
                    },
                    onInputChange: (x, c, N) => {
                      N === "input" && j(c);
                    },
                    renderOption: (x, c) => {
                      const N = c.displayName || "", T = _.trim(), Y = N.toLowerCase().indexOf(T.toLowerCase());
                      if (Y === -1)
                        return /* @__PURE__ */ je(
                          "li",
                          {
                            ...x,
                            key: c.id,
                            style: { lineHeight: 1.5, fontSize: "14px" }
                          },
                          N
                        );
                      const ae = N.substring(0, Y), V = N.substring(
                        Y,
                        Y + T.length
                      ), re = N.substring(
                        Y + T.length
                      );
                      return /* @__PURE__ */ je("li", { ...x, key: c.id }, /* @__PURE__ */ f("span", { className: "inline", children: [
                        ae,
                        /* @__PURE__ */ n("span", { className: "bg-yellow-300", children: V }),
                        re
                      ] }));
                    },
                    renderInput: (x) => /* @__PURE__ */ n(
                      Pe,
                      {
                        ...x,
                        label: "User",
                        variant: "outlined",
                        size: "small",
                        inputRef: M
                      }
                    )
                  }
                )
              }
            ) })
          ] }),
          /* @__PURE__ */ f(b, { className: "flex flex-row flex-2 md:space-x-3 items-center w-full", children: [
            /* @__PURE__ */ n(U, { className: "flex-1", children: s("Role") }),
            /* @__PURE__ */ n(b, { className: "flex-3", children: /* @__PURE__ */ n(
              Tt,
              {
                id: "selectedRoles",
                name: "selectedRoles",
                options: B,
                control: h,
                getOptionLabel: (y) => y == null ? void 0 : y.name,
                dataTestId: "accessrights-select-role"
              }
            ) })
          ] })
        ]
      },
      "specific-section"
    ),
    /* @__PURE__ */ n(b, { className: "flex items-center md:pr-5 justify-end", children: /* @__PURE__ */ n(
      he,
      {
        variant: "contained",
        size: "small",
        onClick: A((y) => {
          var D;
          J(y), L("", [...S, { userId: (D = y.roles) == null ? void 0 : D.id }]), k();
        }),
        children: s("add")
      }
    ) })
  ] });
}
Re.propTypes = {
  translate: i.any,
  permissionDetailsList: i.any,
  getPermissionDetails: i.any,
  onSubmit: i.any,
  permissionTypes: i.any,
  roleList: i.any,
  featureData: i.any
};
function Ue({
  isOpen: s,
  onClose: J,
  permissions: g,
  featureState: S,
  featureName: _
}) {
  const j = () => {
    J();
  }, E = S[_] || !1, O = (I, d = 0) => {
    if (!I) return null;
    const h = I.child || [], A = I.display_name || I.name || I.id;
    return /* @__PURE__ */ f("div", { className: "py-2 ", children: [
      /* @__PURE__ */ f("div", { className: "flex items-center  ", children: [
        E ? /* @__PURE__ */ n(z, { icon: Ct }) : /* @__PURE__ */ n(z, { icon: Jt }),
        /* @__PURE__ */ n("div", { className: "top-6.5 w-4 border-t border-gray-300" }),
        /* @__PURE__ */ n(
          "div",
          {
            className: `
            inline-flex items-center 
            text-[0.8rem]
            px-2 py-1
            rounded-full
            bg-gray-100
            text-gray-800
            border border-gray-300
            hover:bg-gray-200
            transition-all duration-200 cursor-pointer
            
          `,
            children: A
          }
        )
      ] }),
      (h == null ? void 0 : h.length) > 0 && /* @__PURE__ */ n("div", { className: "pl-2 ", children: h.map((k, B) => {
        const L = B === h.length - 1;
        return /* @__PURE__ */ f("div", { className: "relative pl-3", children: [
          /* @__PURE__ */ n(
            "div",
            {
              className: `
                    absolute left-0 w-px bg-gray-300
                    ${L ? "top-0 h-6.5" : "top-[-11px] bottom-0"}
                  `
            }
          ),
          /* @__PURE__ */ n("div", { className: "absolute left-0 top-6.5 w-3 border-t border-gray-300" }),
          O(k, d + 1)
        ] }, B);
      }) })
    ] });
  };
  return /* @__PURE__ */ n(Ae, { open: s, onClose: j, children: /* @__PURE__ */ n(le, { className: "fixed inset-0 flex items-start justify-center z-50  bg-opacity-10", children: /* @__PURE__ */ f(
    Le,
    {
      className: `
          relative mt-10  shadow-lg flex flex-col rounded-xl
          w-[95vw] max-w-md
          sm:w-[80vw] sm:max-w-lg
          md:w-[60vw] md:max-w-xl
          lg:w-[60vw] lg:max-w-2xl
          xl:w-[30vw] xl:max-w-3xl
         
        `,
      children: [
        /* @__PURE__ */ f(b, { className: "flex justify-between items-center p-[5px_10px] border-b border-black", children: [
          /* @__PURE__ */ n(U, { variant: "body1", className: "font-bold text-customBlue", children: "Permissions" }),
          /* @__PURE__ */ n(
            ve,
            {
              size: "small",
              onClick: j,
              "data-testid": "flywayquery-close-button",
              children: /* @__PURE__ */ n(z, { icon: Be })
            }
          )
        ] }),
        /* @__PURE__ */ n("div", { className: " max-h-[75vh] overflow-y-auto", children: g && /* @__PURE__ */ n("div", { className: "w-max pl-6 m-3  rounded px-2 py-1 h-fit ", children: O(g) }) })
      ]
    }
  ) }) });
}
Ue.propTypes = {
  isOpen: i.bool,
  onClose: i.func,
  permissions: i.any,
  featureName: i.any,
  featureState: i.any
};
function qe({ config: s, row: J }) {
  var g;
  const [S, _] = p(null), j = !!S, E = (d) => {
    d.stopPropagation(), _(d.currentTarget), typeof s.menuClick == "function" && s.menuClick(J);
  }, O = (d) => {
    d && d.stopPropagation(), _(null);
  }, I = (d) => (h) => {
    h.stopPropagation(), typeof d.onClick == "function" && d.onClick(J), _(null);
  };
  return /* @__PURE__ */ f(le, { children: [
    /* @__PURE__ */ n(
      ve,
      {
        size: "small",
        disableRipple: !0,
        sx: {
          "&:hover": {
            backgroundColor: "transparent"
          }
        },
        onClick: E,
        "data-testid": s.dataTestId,
        children: s.icon
      }
    ),
    /* @__PURE__ */ n(
      pt,
      {
        anchorEl: S,
        open: j,
        onClose: O,
        anchorOrigin: { vertical: "bottom", horizontal: "right" },
        transformOrigin: { vertical: "top", horizontal: "right" },
        children: (g = s.menuItems) == null ? void 0 : g.map((d, h) => /* @__PURE__ */ n(ht, { onClick: I(d), children: d.label }, h))
      }
    )
  ] });
}
qe.propTypes = {
  config: i.any,
  row: i.any
};
function Bt({
  subMenuId: s,
  // subMenuGroupName,
  subMenuFeatureVal: J,
  // selectedTab,
  parentLoading: g,
  onNewAPIChange: S
}) {
  const _ = At(Lt), j = yt(), E = _e(null), O = _e(!1), I = St(), [d, h] = p([]), [A, k] = p([]), [B, L] = p([]), [y, D] = p([]), [M, x] = p([]), [c, N] = p(""), [T, Y] = p({}), [ae, V] = p(!1), [re, se] = p(!1), [ye, Ye] = p(""), [q, Ve] = p(null), [We, Ge] = p({}), [He, W] = p(!1), [ee, xe] = p(!1), [$e, we] = p(null), [G, Qe] = p([]), [Xe, oe] = p(0), [Ke, Ne] = p(""), { translate: be } = ze(), [Ze, ie] = p(""), [et, de] = p([]), [F, H] = p(null);
  te(() => {
    let e = E.current;
    return () => {
      I("conversion_event", {
        form: e,
        form_name: "Access Rights",
        submit: O.current
      });
    };
  }, []);
  const ce = (e) => {
    var l;
    let r;
    return r = (l = e.userMenuItemDtos) == null ? void 0 : l.toSorted((t, a) => t.designationId !== void 0 && a.designationId !== void 0 ? t.designationId - a.designationId : t.designationId !== void 0 && a.designationId === void 0 ? -1 : t.designationId === void 0 && a.designationId !== void 0 ? 1 : t.userId !== void 0 && a.userId !== void 0 ? t.userId - a.userId : t.userId !== void 0 && a.userId === void 0 ? -1 : t.userId === void 0 && a.userId !== void 0 ? 1 : 0), r;
  };
  i.any;
  const ue = (e) => (e == null || e.userMenuItemDtos.forEach((l) => {
    l.featureJson = ot(
      JSON.parse(e.featureJson || "{}"),
      JSON.parse(l.featureJson || "{}")
    ), l.designationId ? (l.code = "Role", l.displayName = l.roleName) : (l.code = "User", l.displayName = l.fullName);
  }), e), tt = async () => {
    var e, l;
    try {
      if (W((r) => !r), ee) {
        const r = [];
        Object.entries(JSON.parse(q == null ? void 0 : q.featureJson)).forEach(
          ([t, a]) => {
            a === !0 && r.push(t);
          }
        );
        try {
          await Z({
            code: "delete_permissions",
            parameters: {
              permissionList: r,
              roleId: parseInt(q == null ? void 0 : q.designationId),
              userId: parseInt(q == null ? void 0 : q.userId)
            }
          }), C({
            type: "success",
            message: "Permission Deleted Successfully"
          });
          const { data: t } = await K(s);
          $(t);
        } catch {
          C({
            type: "error",
            message: "error occurred"
          });
        }
      } else {
        await xt(ye);
        let { data: r } = await fe(s);
        (r == null ? void 0 : r.userMenuItemDtos.length) > 0 && (r = ue(r)), k(r.userMenuItemDtos);
      }
      V(!1), W((r) => !r);
    } catch (r) {
      C({
        type: "error",
        message: `Error Deleting data: ${(l = (e = r == null ? void 0 : r.response) == null ? void 0 : e.data) == null ? void 0 : l.message}`
      }), W((t) => !t), V(!1);
    }
  }, nt = (e, l) => {
    const r = new Set(e.map((a) => a.id)), t = [];
    return Object.entries(l).forEach(([a, m]) => {
      m === !0 && !r.has(a) && t.push({ id: a, action: "grant" });
    }), e.forEach((a) => {
      l[a.id] || t.push({ id: a.id, action: "revoke" });
    }), t;
  }, { handleSubmit: lt } = ge({}), me = async (e) => {
    var l, r, t, a, m, v;
    try {
      if (ee) {
        e = { ...e, featureJson: JSON.parse(e == null ? void 0 : e.featureJson) };
        const o = nt(
          e.permissions,
          e == null ? void 0 : e.featureJson
        );
        if (((l = o[0]) == null ? void 0 : l.action) === "grant")
          we({
            ...e,
            id: (r = o[0]) == null ? void 0 : r.id
          }), oe(1);
        else if (((t = o[0]) == null ? void 0 : t.action) === "revoke")
          try {
            await Z({
              code: "revoke_permission",
              parameters: {
                featureName: (a = o[0]) == null ? void 0 : a.id,
                roleId: parseInt(e == null ? void 0 : e.designationId),
                userId: parseInt(e == null ? void 0 : e.userId)
              }
            }), C({
              type: "success",
              message: "Permission Revoked Successfully"
            });
          } catch {
            C({
              type: "error",
              message: "Error in revoking permission"
            });
          }
        const { data: w } = await K(s);
        $(w);
      } else
        await Nt(e);
    } catch (o) {
      C({
        type: "error",
        message: `Error Updating data: ${(v = (m = o == null ? void 0 : o.response) == null ? void 0 : m.data) == null ? void 0 : v.message}`
      });
    }
  }, at = async (e) => {
    try {
      if (e = {
        ...e,
        featureJson: JSON.parse(e == null ? void 0 : e.featureJson)
      }, e != null && e.checkAll) {
        const r = Object.keys(e == null ? void 0 : e.featureJson).filter((t) => (e == null ? void 0 : e.featureJson[t]) === !1).join(",");
        await Z({
          code: "grant_permission_bulk",
          parameters: {
            permission_id_list: r,
            role_id: parseInt(e == null ? void 0 : e.designationId),
            user_id: parseInt(e == null ? void 0 : e.userId)
          }
        }), C({
          type: "success",
          message: "Permission granted Successfully"
        });
      }
      const { data: l } = await K(s);
      $(l);
    } catch (l) {
      console.error(l);
    }
  }, Ie = async (e) => {
    var l, r, t;
    if (!(e != null && e.roles || e != null && e.selectedRoles)) {
      C({
        message: "Please select either user or role !!",
        type: "info"
      });
      return;
    }
    if (ee && d.length < 1) {
      C({
        message: "Please add permissions first for this feature !!",
        type: "info"
      });
      return;
    }
    try {
      const a = ((l = e == null ? void 0 : e.selectedRoles) == null ? void 0 : l.map((o) => o == null ? void 0 : o.id)) || [], m = T != null && T.id ? A.some((o) => (o == null ? void 0 : o.userId) === (T == null ? void 0 : T.id)) : !1, v = (a == null ? void 0 : a.length) > 0 ? A.some(
        (o) => a.includes(o == null ? void 0 : o.designationId)
      ) : !1;
      if (m || v)
        C({
          message: "Selected User Already found please select another id",
          type: "warning"
        });
      else {
        const o = a == null ? void 0 : a.join(","), w = {
          userId: (r = e == null ? void 0 : e.roles) == null ? void 0 : r.id,
          designationId: o || null
        }, P = G.filter(
          (u) => {
            var R;
            return (R = u == null ? void 0 : u.id) == null ? void 0 : R.startsWith("view");
          }
        );
        if (ee) {
          we({
            ...w,
            id: (P == null ? void 0 : P.filter((R) => R.id.split(".").length === 3).map((R) => R.id)[0]) || ((t = G[0]) == null ? void 0 : t.id)
          }), oe(1);
          const { data: u } = await K(s);
          $(u);
        } else {
          await wt(s, w);
          let { data: u } = await fe(s);
          (u == null ? void 0 : u.userMenuItemDtos.length) > 0 && (u == null ? void 0 : u.userMenuItemDtos.length) > 0 && (u = ue(u)), N(u == null ? void 0 : u.featureJson);
          const R = ce(u);
          k(R);
          const Q = u.featureJson ? Object.keys(JSON.parse(u.featureJson)) : [];
          if (Q.length > 0) {
            const { data: ut } = await Z({
              code: "retrieve_display_name_for_feature",
              parameters: {
                menu_id: s,
                feature_name_list: Q
              }
            });
            h(ut.result);
          } else
            h([]);
          C({
            message: "menu item added successfully",
            type: "success"
          });
        }
        O.current = !0, Y({});
      }
    } catch (a) {
      console.error(a), C({
        message: "cannot add menu item",
        type: "error"
      });
    }
  }, rt = gt(
    mt((e) => {
      if (!e)
        k(B);
      else {
        const l = B == null ? void 0 : B.filter(
          (r) => {
            var t, a;
            return r != null && r.designationId ? (t = r.roleName) == null ? void 0 : t.toLowerCase().includes(e) : (a = r.fullName) == null ? void 0 : a.toLowerCase().includes(e);
          }
        );
        I("search_tracking", {
          searchTerm: e,
          results_count: l.length,
          search_type: "Page Search"
        }), k(l);
      }
    }, 500),
    [d, I]
  ), st = (e) => {
    const l = e.target.value.toLowerCase();
    Ne(l), rt(l);
  }, ot = (e, l = {}) => {
    const r = {};
    return Object.keys(e).forEach((t) => {
      Object.prototype.hasOwnProperty.call(l, t) ? r[t] = l[t] : r[t] = e[t];
    }), JSON.stringify(r);
  }, it = (e, l) => {
    const r = new Set(l.map((a) => a.id)), t = {};
    return e.forEach((a) => {
      t[a.id] = r.has(a.id);
    }), JSON.stringify(t);
  }, $ = (e) => {
    e == null || e.userMenuItemDtos.forEach((t) => {
      t.id = (t == null ? void 0 : t.designationId) || (t == null ? void 0 : t.userId), t.featureJson = it(
        e == null ? void 0 : e.permissions,
        t == null ? void 0 : t.permissions
      ), t.designationId ? (t.code = "Role", t.displayName = t.roleName) : (t.code = "User", t.displayName = t.fullName);
    });
    const l = [
      ...new Set(e.permissions.map((t) => t.id))
    ];
    h(l), Qe(e == null ? void 0 : e.permissions);
    const r = ce(e);
    k(r), L(r);
  };
  te(() => {
    (async () => {
      var e, l, r;
      try {
        if (s) {
          H(null), Se(!1), W((o) => !o), Ne("");
          let t, a;
          if (J ? (t = (await K(s)).data, a = !0, xe(!0), S({ id: s, val: !0 })) : (t = (await fe(s)).data, a = !1, xe(!1), S({ id: s, val: !1 })), a)
            $(t);
          else {
            (t == null ? void 0 : t.userMenuItemDtos.length) > 0 && (t = ue(t)), N(t == null ? void 0 : t.featureJson);
            const o = ce(t);
            k(o), L(o);
          }
          let m = M;
          if (!y || y.length === 0) {
            const { data: o } = await bt();
            x(o), m = o;
          }
          let v;
          if (a)
            v = t.permissions.map((o) => o.id), h(v);
          else if (v = t.featureJson ? Object.keys(JSON.parse(t.featureJson)) : [], v.length > 0) {
            const [o] = await Promise.all([
              await Z({
                code: "retrieve_display_name_for_feature",
                parameters: {
                  menu_id: s,
                  feature_name_list: v
                }
              })
            ]);
            h((e = o.data) == null ? void 0 : e.result);
          } else
            h([]);
          if (m && m.length > 0)
            if (t.isDynamicFeature) {
              const o = JSON.parse(JSON.stringify(m)).filter((w) => {
                const P = w.roleType;
                return P === null || t != null && t.isMobileFeature && t != null && t.isWebFeature ? !0 : t.isMobileFeature ? P === "MOBILE" || P === "BOTH" : t.isWebFeature ? P === "WEB" || P === "BOTH" : !1;
              });
              D(o);
            } else
              D(m);
          W((o) => !o);
        }
      } catch (t) {
        C({
          type: "error",
          message: `Error loading initial data: ${(r = (l = t == null ? void 0 : t.response) == null ? void 0 : l.data) == null ? void 0 : r.message}`
        }), W((a) => !a);
      }
    })();
  }, [s, S]);
  function ne(e, l) {
    for (const r of e)
      if (String(r.id) === String(l))
        return r;
    return null;
  }
  const [dt, Se] = p(!1), ct = (e) => (l, r) => {
    Se(r ? e : !1);
  };
  return /* @__PURE__ */ n(Oe, { children: (He || g) && _ ? /* @__PURE__ */ n("div", { className: "w-full flex flex-wrap", children: /* @__PURE__ */ f("div", { className: "w-full flex flex-col px-2", children: [
    /* @__PURE__ */ n("div", { className: "bg-gray-300 animate-pulse rounded-sm h-[70px] mb-2" }),
    /* @__PURE__ */ n("div", { className: "bg-gray-300 animate-pulse rounded-sm h-[280px] mb-2" })
  ] }) }) : /* @__PURE__ */ f(b, { container: !0, sx: { borderTop: `1px solid ${j.palette.divider}` }, children: [
    /* @__PURE__ */ n(
      vt,
      {
        description: "Are you sure , Do you want to delete this ?",
        title: "CONFIRM ACTION",
        open: ae && ye === (q == null ? void 0 : q.id),
        handleClick: tt,
        handleClose: () => V((e) => !e),
        dataTestId: "accessrights-delete-modal"
      }
    ),
    /* @__PURE__ */ n(
      Ue,
      {
        isOpen: re && F,
        onClose: () => {
          se((e) => !e), H(null), ie(""), de([]);
        },
        featureState: et,
        featureName: Ze,
        permissions: F
      }
    ),
    /* @__PURE__ */ n(
      Fe,
      {
        isOpen: Xe === 1,
        onClose: () => oe(0),
        pendingGrant: $e,
        subMenuId: s,
        newApiData: $
      }
    ),
    /* @__PURE__ */ n(
      "form",
      {
        ref: E,
        onSubmit: lt(Ie),
        className: "w-full",
        children: /* @__PURE__ */ f(
          b,
          {
            container: !0,
            className: "flex flex-col md:flex-row items-center justify-between  p-2 w-full",
            spacing: 1,
            children: [
              /* @__PURE__ */ f(b, { className: "flex-1 flex space-x-10 items-center justify-between", children: [
                /* @__PURE__ */ n(U, { variant: "body2", children: be("Search") }),
                /* @__PURE__ */ n(le, { children: /* @__PURE__ */ n(
                  Pe,
                  {
                    id: "searchQuery",
                    placeholder: "Search Text",
                    size: "small",
                    onChange: st,
                    value: Ke,
                    "data-testid": "access-rights-textfield-search",
                    sx: {
                      "& .MuiInputBase-root": {
                        height: "2.6em"
                      }
                    }
                  }
                ) })
              ] }),
              /* @__PURE__ */ n(b, { className: "flex-3 flex space-x-10 items-center justify-between w-full", children: /* @__PURE__ */ n(
                Re,
                {
                  translate: be,
                  onSubmit: Ie,
                  roleList: y,
                  featureData: A
                }
              ) })
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ n("div", { style: { width: "100%" }, children: A.map((e) => /* @__PURE__ */ n(Oe, { children: /* @__PURE__ */ f(
      Et,
      {
        expanded: dt === `panel${e == null ? void 0 : e.id}`,
        onChange: ct(`panel${e == null ? void 0 : e.id}`),
        children: [
          /* @__PURE__ */ f(
            Pt,
            {
              expandIcon: /* @__PURE__ */ n(z, { icon: Dt }),
              "aria-controls": "panel1bh-content",
              id: "panel1bh-header",
              children: [
                /* @__PURE__ */ n(
                  U,
                  {
                    component: "span",
                    sx: { width: "33%", flexShrink: 0 },
                    children: e.code
                  }
                ),
                /* @__PURE__ */ n(
                  U,
                  {
                    component: "span",
                    sx: { color: "text.secondary" },
                    children: e.displayName
                  }
                ),
                /* @__PURE__ */ f("div", { className: "ml-auto mr-4 flex items-center space-x-3", children: [
                  /* @__PURE__ */ n(
                    z,
                    {
                      icon: Ot,
                      style: {
                        cursor: "pointer",
                        color: j.palette.error.main,
                        fontSize: "16px",
                        marginTop: "0.5rem"
                      },
                      onClick: (l) => {
                        l.stopPropagation(), l.preventDefault(), V(!0), Ye(e.id), Ve(e);
                      }
                    }
                  ),
                  /* @__PURE__ */ n(
                    qe,
                    {
                      config: {
                        label: "",
                        icon: /* @__PURE__ */ n(
                          z,
                          {
                            style: {
                              cursor: "pointer",
                              // color: theme.palette.error.main,
                              fontSize: "16px",
                              marginTop: "0.5rem"
                            },
                            icon: kt
                          }
                        ),
                        dataTestId: "accessrights-edit-icon",
                        menuClick: (l) => {
                          Ge(() => ({
                            ...l,
                            code: l.designationId ? "Role" : "User",
                            menuConfigId: s,
                            displayName: l.designationId ? l.roleName : l.fullName
                          }));
                        },
                        menuItems: [
                          {
                            label: "Check All",
                            onClick: (l) => {
                              if (ee)
                                at({
                                  ...l,
                                  checkAll: !0
                                });
                              else {
                                let r = JSON.parse(c);
                                const t = (d == null ? void 0 : d.length) > 0 ? d.reduce(
                                  (a, { feature_name: m }) => (a[m] = !0, a),
                                  {}
                                ) : Object.keys(r).reduce(
                                  (a, m) => (a[m] = !0, a),
                                  {}
                                );
                                k(
                                  (a) => a.map(
                                    (m) => m.id === l.id ? {
                                      ...m,
                                      featureJson: JSON.stringify(t)
                                    } : m
                                  )
                                ), me({
                                  ...We,
                                  featureJson: JSON.stringify(t)
                                });
                              }
                            }
                          }
                        ]
                      },
                      row: e
                    }
                  )
                ] })
              ]
            }
          ),
          /* @__PURE__ */ n(Mt, { children: /* @__PURE__ */ n("div", { className: "overflow-x-auto", children: /* @__PURE__ */ n("div", { className: "flex gap-6 w-max", children: /* @__PURE__ */ f("div", { className: "grid grid-cols-3 w-max p-0 m-0", children: [
            d.length <= 0 && Object.keys(JSON.parse(c || "{}")).length <= 0 && /* @__PURE__ */ n("div", { className: "text-gray-500 px-4 italic", children: "No Data to Display" }),
            (d == null ? void 0 : d.length) > 0 ? Object.keys(
              JSON.parse(e.featureJson || "{}")
            ).map((l, r) => {
              var t, a;
              const m = JSON.parse(
                e.featureJson || "{}"
              ), v = ((t = d.find(
                (u) => u.feature_name === l
              )) == null ? void 0 : t.display_name) || l, o = m[l] || !1, w = ne(
                G,
                v
              ), P = (((a = w == null ? void 0 : w.child) == null ? void 0 : a.length) || 0) > 0;
              return /* @__PURE__ */ f(
                ke,
                {
                  className: "p-0 flex  ",
                  children: [
                    /* @__PURE__ */ n(
                      De,
                      {
                        control: /* @__PURE__ */ n(
                          Ce,
                          {
                            checked: o,
                            name: l,
                            onClick: () => {
                              const u = {
                                ...m,
                                [l]: !o
                              };
                              k(
                                (R) => R.map(
                                  (Q) => Q.id === e.id ? {
                                    ...Q,
                                    featureJson: JSON.stringify(
                                      u
                                    )
                                  } : Q
                                )
                              ), me({
                                ...e,
                                featureJson: JSON.stringify(
                                  u
                                ),
                                code: e.designationId ? "Role" : "User",
                                menuConfigId: s,
                                displayName: e.designationId ? e.roleName : e.fullName
                              });
                            }
                          }
                        ),
                        label: /* @__PURE__ */ n(U, { variant: "body2", children: (() => {
                          const u = ne(
                            G,
                            v
                          );
                          return u ? u.name : v;
                        })() })
                      }
                    ),
                    P && /* @__PURE__ */ n(
                      "div",
                      {
                        onClick: () => {
                          if ((F == null ? void 0 : F.id) === (w == null ? void 0 : w.id)) {
                            H(null), se(!1), ie(""), de([]);
                            return;
                          }
                          ie(l), de(
                            m
                          ), se(!0), H(w);
                        },
                        className: "cursor-pointer text-gray-600 transition-transform duration-200 hover:scale-[1.2] py-1 pr-3",
                        children: (F == null ? void 0 : F.id) === (w == null ? void 0 : w.id) ? /* @__PURE__ */ n(Je, { title: "Close Permissions", children: /* @__PURE__ */ n(
                          z,
                          {
                            color: "primary",
                            icon: Te
                          }
                        ) }) : /* @__PURE__ */ n(Je, { title: "View Permissions", children: /* @__PURE__ */ n(
                          z,
                          {
                            className: " text-[var(--color-primary)] ",
                            color: "primary",
                            icon: Ee
                          }
                        ) })
                      }
                    )
                  ]
                },
                `featureName-${r}`
              );
            }) : Object.keys(JSON.parse(c || "{}")).map(
              (l, r) => {
                var t;
                const a = JSON.parse(
                  e.featureJson || "{}"
                ), m = a[l] || !1, v = ne(
                  G,
                  l
                ), o = (((t = v == null ? void 0 : v.child) == null ? void 0 : t.length) || 0) > 0;
                return /* @__PURE__ */ f(
                  ke,
                  {
                    className: "p-0",
                    children: [
                      /* @__PURE__ */ n(
                        De,
                        {
                          control: /* @__PURE__ */ n(
                            Ce,
                            {
                              checked: m,
                              name: l,
                              onClick: () => {
                                const w = {
                                  ...a,
                                  [l]: !m
                                };
                                k(
                                  (P) => P.map(
                                    (u) => u.id === e.id ? {
                                      ...u,
                                      featureJson: JSON.stringify(
                                        w
                                      )
                                    } : u
                                  )
                                ), me({
                                  ...e,
                                  featureJson: JSON.stringify(
                                    w
                                  ),
                                  code: e.designationId ? "Role" : "User",
                                  menuConfigId: s,
                                  displayName: e.designationId ? e.roleName : e.fullName
                                });
                              }
                            }
                          ),
                          label: /* @__PURE__ */ n(U, { variant: "body2", children: (() => {
                            const w = ne(
                              G,
                              l
                            );
                            return w ? w.name : l;
                          })() })
                        }
                      ),
                      o && /* @__PURE__ */ n(
                        "div",
                        {
                          onClick: () => {
                            if ((F == null ? void 0 : F.id) === (v == null ? void 0 : v.id)) {
                              H(null);
                              return;
                            }
                            H(v);
                          },
                          className: "cursor-pointer text-slate-500 dark:text-slate-400 transition-transform duration-200 hover:scale-[1.2] py-1 pr-3",
                          children: (F == null ? void 0 : F.id) === (v == null ? void 0 : v.id) ? /* @__PURE__ */ n(
                            z,
                            {
                              color: "primary",
                              icon: Te
                            }
                          ) : /* @__PURE__ */ n(
                            z,
                            {
                              className: " text-[var(--color-primary)] ",
                              color: "primary",
                              icon: Ee
                            }
                          )
                        }
                      )
                    ]
                  },
                  `featureName-${r}`
                );
              }
            )
          ] }) }) }) })
        ]
      }
    ) })) })
  ] }) });
}
Bt.propTypes = {
  subMenuId: i.any,
  subMenuGroupName: i.any,
  selectedTab: i.any,
  parentLoading: i.any,
  isNewApi: i.any,
  setIsNewApi: i.any,
  onNewAPIChange: i.any,
  subMenuFeatureVal: i.any
};
export {
  Bt as default
};
//# sourceMappingURL=AccessRights-BMRM1u9S-D1Gc0rKI.js.map
