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