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