import { jsxs as r, jsx as t, Fragment as L } from "react/jsx-runtime";
import u from "@/common/services/util/GeneralUtil";
import { useState as m, useEffect as ce, Suspense as H, lazy as Q } from "react";
import { Box as p, Card as T, Typography as d, Button as C, TextField as K, Switch as de, Chip as $ } from "@mui/material";
import { alpha as S } from "@mui/material/styles";
import { useTranslateProvider as me } from "@/common/languageTranslator/TranslationContext";
import { api as h } from "@/common/interceptors/AxiosInterceptor";
import { getRoleList as _ } from "@/common/services/GlobalApis.js";
import { getAssignedFeatures as ue } from "@/utils/feature.js";
import { showToast as x } from "@/common/toaster/toaster";
import { FontAwesomeIcon as fe } from "@fortawesome/react-fontawesome";
import { faTrash as he } from "@fortawesome/free-solid-svg-icons";
import pe from "@/hooks/useTrackEvent";
import z from "prop-types";
import { useSelector as X } from "react-redux";
import { getUseSkeleton as ge } from "@/store/reducers/SkeletonReducer";
const j = () => h.get("/role"), xe = (l) => h.delete(u.isTecho ? `/menuconfig/usermenuitem/delete?empMenuItemId=${l}` : `/menuconfig/usermenuitem/${l}`), ve = (l) => h.get(u.isTecho ? `/role/retrieveById?id=${l}` : `/role/${l}`), Oe = (l) => h.post("/role", { ...l }), Be = (l) => u.isTecho ? h.put("/role/update", { ...l }) : h.post("/role", { ...l }), be = (l) => h.put(`role/?is_active=${l.state === "INACTIVE" ? "true" : "false"}`, {
  ...l
}), De = (l, n) => h.post(`/menuconfig/assignnewfeature?roleId=${n}`, { ...l }), Z = ({ children: l, isLoading: n = !0 }) => !X(ge) || !n ? l : /* @__PURE__ */ r("div", { className: "pt-6 relative h-[90vh]", children: [
  /* @__PURE__ */ r("div", { className: "flex flex-row  h-[80vh] ", children: [
    /* @__PURE__ */ r("div", { className: "flex flex-col border border-gray-300 w-[20%] p-2 mr-3 rounded-md", children: [
      " ",
      /* @__PURE__ */ r("div", { className: "flex justify-between", children: [
        /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-23 h-[40px] mr-3" }),
        /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-40 h-[40px]" })
      ] }),
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm mt-2 w-full h-[50px]" }),
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm mt-2 w-full h-full" })
    ] }),
    /* @__PURE__ */ r("div", { className: "flex flex-col border border-gray-300 w-[80%] p-2 rounded-md", children: [
      /* @__PURE__ */ r("div", { className: "flex justify-between", children: [
        /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-24 h-[40px]" }),
        /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-21 h-[40px]" })
      ] }),
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm mt-2 w-full h-[50px]" }),
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm mt-2 w-full h-full" })
    ] })
  ] }),
  /* @__PURE__ */ t("div", { className: "absolute bottom-20 right-[10px] ", children: /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-full w-[40px] h-[40px]" }) })
] });
Z.propTypes = {
  children: z.any,
  loading: z.any,
  isLoading: z.any
};
const ye = Q(() => import("./AddFeatures-CE5rBxEG.js")), we = Q(() => import("./ManageRole-Cbs9dUhc.js"));
function Ne() {
  var q;
  const { translate: l } = me(), [n, b] = m(""), [o, y] = m(n[0]), [A, ee] = m(!1), [V, f] = m(!1), [O, B] = m(!1), [F, D] = m(0), [U, k] = m(""), [w, W] = m(""), [c, te] = m({}), Y = pe(), P = X((e) => e.Authenticate.user.roleId), [E, ae] = m([]), N = async (e = !1) => {
    var a;
    try {
      f(!0);
      const s = A ? j() : _();
      let i, g = [];
      if (P) {
        const [{ data: v }, M] = await Promise.all([
          s,
          ve(P)
        ]);
        i = v, g = ((a = M == null ? void 0 : M.data) == null ? void 0 : a.roleIds) || [];
      } else {
        const { data: v } = await s;
        i = v;
      }
      ae(g);
      const R = g.length > 0 ? i.filter((v) => g.includes(v.id)) : i;
      b(R), !e && R.length > 0 && y(R[0]);
    } catch (s) {
      console.error(s), x({ message: "Error in getting role data", type: "error" });
    } finally {
      f(!1);
    }
  };
  ce(function() {
    (async () => {
      const { data: a } = await ue("techo.manage.role");
      a && te(JSON.parse(a));
    })(), N();
  }, []);
  const se = async (e) => {
    let a = e.target.checked;
    ee(e.target.checked);
    try {
      f((i) => !i);
      let s;
      a ? { data: s } = await j() : { data: s } = await _(), E && E.length > 0 && (s = s.filter(
        (i) => E.includes(i.id)
      )), b(s), y(s[0]), f((i) => !i), k("");
    } catch (s) {
      console.error(s), x({ message: "Error in getting role data", type: "error" }), f((i) => !i);
    }
  }, J = n ? n == null ? void 0 : n.filter(
    (e) => e.name.toLowerCase().includes(U.toLowerCase())
  ) : [], re = (e) => {
    if (!e) return "";
    const a = new Date(Number(e)), s = String(a.getDate()).padStart(2, "0"), i = String(a.getMonth() + 1).padStart(2, "0"), g = a.getFullYear();
    return `${s}/${i}/${g}`;
  }, le = async () => {
    try {
      const e = n == null ? void 0 : n.find((s) => s.id === o.id);
      await be(e), x({
        message: `State succesfully changed from  ${(e == null ? void 0 : e.state) === "INACTIVE" ? "inactive" : "active"} to ${(e == null ? void 0 : e.state) === "INACTIVE" ? "active" : "inactive"}`,
        type: "success"
      });
      let a;
      f((s) => !s), A ? a = await j() : a = await _(), b(a.data), y(a.data[0]), f((s) => !s);
    } catch (e) {
      console.error(e), x({ message: "Error in handle active", type: "error" }), f((a) => !a);
    }
  }, I = n ? (q = n.find((e) => e.id === o.id)) == null ? void 0 : q.assignedFeatureList.filter(
    (e) => {
      var a;
      return (a = e.featureName) == null ? void 0 : a.toLowerCase().includes(w == null ? void 0 : w.toLowerCase());
    }
  ).sort((e, a) => {
    var s;
    return (s = e.featureName) == null ? void 0 : s.localeCompare(a.featureName);
  }) : [], oe = async (e) => {
    try {
      await xe(e.userMenuItemId), await N(!0), W(""), x({ message: "Feature deleted successfully!", type: "success" });
    } catch (a) {
      x({ message: a, type: "error" });
    }
  }, G = (e) => {
    D(e), Y("button_click", {
      button_name: `${e === 1 ? "add" : "edit"} role modal button`,
      button_type: "navigate",
      button_id: `roles-${e === 1 ? "add" : "edit"}-button`
    });
  }, ne = () => {
    N(), k("");
  }, ie = async () => {
    try {
      B(!0), await Y("button_click", {
        button_name: "add feature button",
        button_type: "navigate",
        button_id: "roles-addfeatures-button-add"
      });
    } catch (e) {
      console.error(e);
    }
  };
  return u.isTecho && !V && !(c != null && c["view.manage.role"]) ? /* @__PURE__ */ t(p, { className: "flex justify-center items-center w-full h-[80vh]", children: /* @__PURE__ */ t(
    T,
    {
      className: "h-80 w-150 flex justify-center items-center",
      children: /* @__PURE__ */ t(d, { variant: "h5", className: "text-customBlue", children: "You dont have permission to view Roles" })
    }
  ) }) : /* @__PURE__ */ t(Z, { isLoading: V, children: /* @__PURE__ */ r(p, { className: "flex flex-col gap-4 p-4 min-[900px]:flex-row min-[900px]:h-[calc(100vh-80px)]", children: [
    /* @__PURE__ */ r(
      T,
      {
        variant: "outlined",
        className: "w-full min-[900px]:w-[300px] flex flex-col p-4",
        children: [
          /* @__PURE__ */ r("div", { className: "flex justify-between items-center mb-3", children: [
            /* @__PURE__ */ t(
              d,
              {
                variant: "h6",
                fontWeight: 600,
                className: "text-customBlue",
                children: "User Roles"
              }
            ),
            (!u.isTecho || (c == null ? void 0 : c["create.manage.role"])) && /* @__PURE__ */ t(
              C,
              {
                size: "small",
                variant: "contained",
                color: "primary",
                onClick: () => G(1),
                "data-testid": "managerole-add-button",
                children: l("+ Add Role")
              }
            )
          ] }),
          /* @__PURE__ */ t(
            K,
            {
              size: "small",
              variant: "outlined",
              placeholder: "Search roles...",
              fullWidth: !0,
              value: U,
              onChange: (e) => k(e.target.value),
              "data-testid": "listofroles-search-input"
            }
          ),
          /* @__PURE__ */ r("div", { className: "flex items-center gap-2 mt-3", children: [
            /* @__PURE__ */ t(
              de,
              {
                size: "small",
                checked: A,
                onChange: se
              }
            ),
            /* @__PURE__ */ t(d, { variant: "body2", children: "Include Inactive" })
          ] }),
          /* @__PURE__ */ t("div", { className: "flex-1 overflow-y-auto mt-4", children: J.length > 0 && /* @__PURE__ */ t(L, { children: J.map((e) => /* @__PURE__ */ r(
            T,
            {
              variant: "outlined",
              onClick: () => y(e),
              className: `p-3 cursor-pointer transition
                  ${o.id === e.id ? "border-b-2" : "border-b-2 border-0"}`,
              sx: o.id === e.id ? {
                bgcolor: (a) => S(a.palette.primary.main, 0.08)
              } : {},
              children: [
                /* @__PURE__ */ r(d, { fontWeight: 600, children: [
                  e.name,
                  "     ",
                  (e == null ? void 0 : e.state) === "INACTIVE" && /* @__PURE__ */ t($, { label: "INACTIVE", color: "disabled", size: "small" })
                ] }),
                /* @__PURE__ */ r(d, { variant: "body2", color: "text.secondary", children: [
                  e.assignedFeatureList.length,
                  " Features"
                ] })
              ]
            },
            e.id
          )) }) })
        ]
      }
    ),
    /* @__PURE__ */ r(
      T,
      {
        variant: "outlined",
        className: "w-full min-[900px]:flex-1 flex flex-col p-5",
        children: [
          /* @__PURE__ */ r("div", { className: "flex flex-col sm:flex-row justify-between items-start border-b pb-4 gap-4", children: [
            /* @__PURE__ */ r("div", { className: "flex flex-col gap-1 w-full sm:w-auto", children: [
              /* @__PURE__ */ r("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ t(
                  d,
                  {
                    variant: "h5",
                    fontWeight: 600,
                    className: "text-customBlue",
                    children: (o == null ? void 0 : o.name) || "Select Role"
                  }
                ),
                (o == null ? void 0 : o.state) === "ACTIVE" && /* @__PURE__ */ t($, { label: "ACTIVE", color: "success", size: "small" }),
                (o == null ? void 0 : o.state) === "INACTIVE" && /* @__PURE__ */ t($, { label: "INACTIVE", color: "disabled", size: "small" })
              ] }),
              /* @__PURE__ */ r(
                d,
                {
                  variant: "body2",
                  color: "text.secondary",
                  className: "mt-1",
                  children: [
                    "Created on ",
                    re(o == null ? void 0 : o.createdOn)
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ r("div", { className: "flex gap-2", children: [
              (!u.isTecho || (c == null ? void 0 : c["update.manage.role.toggleActive"])) && /* @__PURE__ */ t(
                C,
                {
                  variant: "outlined",
                  size: "small",
                  onClick: () => le(),
                  children: (o == null ? void 0 : o.state) === "ACTIVE" ? "Deactivate" : "Activate"
                }
              ),
              (!u.isTecho || (c == null ? void 0 : c["update.manage.role"])) && /* @__PURE__ */ t(
                C,
                {
                  variant: "contained",
                  size: "small",
                  onClick: () => G(2),
                  children: "✏️ Edit Role"
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ r("div", { className: "mt-5 flex flex-col flex-1 overflow-hidden", children: [
            /* @__PURE__ */ r("div", { className: "flex flex-col sm:flex-row justify-between items-start sm:items-center mb-4 gap-4", children: [
              /* @__PURE__ */ r("div", { className: "flex flex-row items-center gap-2 w-full sm:w-auto", children: [
                /* @__PURE__ */ t(d, { fontWeight: 600, children: l("Assigned Features") }),
                /* @__PURE__ */ r(d, { variant: "body2", color: "text.secondary", children: [
                  "(",
                  I.length,
                  " ",
                  l("features active for this role"),
                  ")"
                ] })
              ] }),
              /* @__PURE__ */ t(
                K,
                {
                  size: "small",
                  sx: { width: { xs: "100%", sm: "60%" } },
                  placeholder: "Search Feature Name",
                  variant: "outlined",
                  value: w,
                  onChange: (e) => W(e.target.value),
                  "data-testid": "assignedfeatures-search-input"
                }
              )
            ] }),
            /* @__PURE__ */ r(p, { className: "overflow-x-auto w-full", children: [
              /* @__PURE__ */ r(
                p,
                {
                  className: "grid grid-cols-[minmax(340px,1.5fr)_120px] px-4 py-2 text-[15px] font-semibold border-b min-w-[500px]",
                  sx: {
                    color: "text.secondary",
                    bgcolor: (e) => S(e.palette.action.hover, 0.04)
                  },
                  children: [
                    /* @__PURE__ */ t("div", { children: l("FEATURE NAME") }),
                    /* @__PURE__ */ t("div", { className: "text-center", children: l("ACTIONS") })
                  ]
                }
              ),
              /* @__PURE__ */ r(
                p,
                {
                  className: "h-[calc(100vh-440px)] overflow-y-auto min-w-[500px]",
                  sx: {
                    bgcolor: "background.paper"
                  },
                  children: [
                    I.length > 0 && /* @__PURE__ */ t(L, { children: I.map((e, a) => /* @__PURE__ */ r(
                      p,
                      {
                        className: "grid grid-cols-[minmax(340px,1.5fr)_120px] px-4 py-3 items-center border-b last:border-b-0 transition",
                        sx: {
                          "&:hover": {
                            bgcolor: (s) => S(s.palette.action.hover, 0.04)
                          }
                        },
                        children: [
                          /* @__PURE__ */ t("div", { className: "flex flex-col", children: /* @__PURE__ */ t(d, { sx: { fontSize: "13px", fontWeight: 600 }, children: e.featureName }) }),
                          /* @__PURE__ */ t("div", { className: "flex justify-center", children: (!u.isTecho || (c == null ? void 0 : c["view.manage.role.unassignFeature"])) && /* @__PURE__ */ t(
                            fe,
                            {
                              icon: he,
                              onClick: () => {
                                oe(e);
                              },
                              color: "error",
                              className: "text-red-400 cursor-pointer",
                              "data-testid": `assignedfeatures-delete-icon-${a}`
                            }
                          ) })
                        ]
                      },
                      e.id
                    )) }),
                    I.length === 0 && /* @__PURE__ */ t(L, { children: /* @__PURE__ */ t(
                      d,
                      {
                        className: "p-4",
                        sx: { fontSize: "13px", fontStyle: "italic" },
                        children: "No Features assigned yet!"
                      }
                    ) })
                  ]
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ t(
            p,
            {
              className: "border-t p-4",
              sx: {
                bgcolor: (e) => S(e.palette.primary.main, 0.06)
              },
              children: (!u.isTecho || (c == null ? void 0 : c["view.manage.role.assignFeature"])) && /* @__PURE__ */ t(C, { variant: "outlined", size: "small", onClick: ie, children: "+ Add More Features" })
            }
          )
        ]
      }
    ),
    /* @__PURE__ */ t(H, { children: /* @__PURE__ */ t(
      we,
      {
        isUpdate: F !== 1,
        selectedId: F === 2 ? o.id : null,
        "data-testid": "roles-managerole-add-button",
        open: F,
        setOpen: D,
        isRoleListModified: ne
      }
    ) }),
    /* @__PURE__ */ t(H, { fallback: /* @__PURE__ */ t("div", { className: "animate-pulse w-80 h-20 " }), children: O === !0 && /* @__PURE__ */ t(
      ye,
      {
        open: O,
        setOpenModal: B,
        selectedId: o.id,
        setData: () => N(!0),
        assignedFeatureList: n ? (() => {
          var e, a, s;
          return (e = n == null ? void 0 : n.find((i) => (i == null ? void 0 : i.id) === o.id)) != null && e.assignedFeatureList ? (a = n == null ? void 0 : n.find((i) => (i == null ? void 0 : i.id) === o.id)) == null ? void 0 : a.assignedFeatureList : (s = n[0]) == null ? void 0 : s.assignedFeatureList;
        })() : [],
        "data-testid": "roles-addfeatures-component"
      }
    ) })
  ] }) });
}
const Ue = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Ne
}, Symbol.toStringTag, { value: "Module" }));
export {
  Ue as R,
  Be as a,
  Oe as b,
  ve as g,
  De as p
};
//# sourceMappingURL=RoleManagement-BThAL5LO.js.map
