import { jsx as l, jsxs as p, Fragment as ge } from "react/jsx-runtime";
import { useTranslateProvider as lt } from "@/common/languageTranslator/TranslationContext";
import { L as rt, c as _t, g as Ut, v as Ke, S as Ft, j as $t, f as Rt, p as Bt } from "./UserListSkeleton-cglK2SaU-B_Tj5gUp.js";
import { showToast as b } from "@/common/toaster/toaster.jsx";
import Pt from "@/hooks/usePagination.js";
import { getAssignedFeatures as Mt } from "@/utils/feature.js";
import Qe from "@/views/custom-components/CustomConfirmationModal.jsx";
import Ht from "@/views/custom-components/CustomizedTable/CustomizedTableV2";
import Vt from "@/views/custom-components/SideOverlay.jsx";
import f from "prop-types";
import { useState as n, useRef as Dt, useMemo as jt, useEffect as te, useCallback as zt, Suspense as qt, lazy as Yt } from "react";
import { Box as C, Card as Gt, Typography as We, TextField as Jt, CircularProgress as Xe, Button as Ae, Tooltip as Kt, InputLabel as Se, Switch as Qt } from "@mui/material";
import A from "@mui/material/Grid2";
import Ze from "@/views/custom-components/CustomDropdown";
import { useForm as Wt, FormProvider as Xt } from "react-hook-form";
import at from "@/hooks/useTrackEvent";
import { showToast as Zt } from "@/common/toaster/toaster";
import { useDispatch as ot, useSelector as el } from "react-redux";
import { setUserDetails as Le } from "@/store/reducers/AuthenticationReducer";
import { useNavigate as tl, useLocation as nt } from "react-router";
import ye from "@/common/services/util/GeneralUtil";
import { useTheme as ll, alpha as N } from "@mui/material/styles";
import { execute as rl } from "@/common/services/QueryBuilder";
import { faPen as al, faBars as ol, faFilePdf as et, faFileExcel as tt, faUsers as nl, faCheckCircle as sl, faTimesCircle as il, faUserShield as dl, faPhone as cl, faHospital as ul } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon as R } from "@fortawesome/react-fontawesome";
import { A as ml } from "./FileSaver.min-CN9EpL2h-N-3OFAd7.js";
import { E as ee } from "./xlsx.min-D1LFqt_b-BGwkpd8r.js";
import fl from "@/hooks/useDownloadPdf.js";
import ve from "@/views/custom-components/CustomStatsComponent.jsx";
import './UserList-S5Q76wO7.css';const pl = Yt(
  () => import("@/views/feature-components/LocationDirective/LocationDirectiveV2")
), st = ({
  handleOverlayState: le,
  setIsLoading: D,
  isLoading: j,
  setLocationId: re,
  setRoleDetails: ae,
  roleDetails: z,
  status: q,
  setStatus: Y,
  selectedLocation: G,
  setSelectedLocation: be,
  filterRequired: L,
  setUserFilterPreference: ne,
  user: E,
  setFilterRequired: se,
  locationIdRef: ie,
  locations: de,
  setLocations: O,
  setAdminRoleIdsStats: w
}) => {
  const [U, J] = n([]), ce = at(), { translate: u } = lt(), ue = Wt({ mode: "onChange" }), Ne = ot(), K = nt(), {
    control: a,
    handleSubmit: B,
    formState: { errors: Q },
    getValues: _,
    setValue: v,
    clearErrors: xe
  } = ue, x = async () => {
    var m, P, T, I;
    try {
      const { data: y } = await rt({}, { showLoader: !1 });
      J(y), z != null && z.id && v("roleId", z.id), q && v("status", q), ((m = Object.keys((E == null ? void 0 : E.userFilterPreference) || {})) == null ? void 0 : m.length) > 0 && ((P = K == null ? void 0 : K.state) == null ? void 0 : P.fromManageUser) === !0 && (v("roleId", (T = E == null ? void 0 : E.userFilterPreference) == null ? void 0 : T.roleid), v("status", (I = E == null ? void 0 : E.userFilterPreference) == null ? void 0 : I.status));
    } catch (y) {
      console.error(y);
    }
  };
  te(() => {
    x();
  }, []);
  const me = async () => {
    var m, P;
    try {
      D((F) => !F), w([]), ce("button_click", {
        button_name: "User Filter-filter-button",
        button_type: "filter",
        button_id: "userfilterform-search-button"
      });
      const T = _("status") || "BOTH";
      T && Y(T);
      const I = {
        limit: 50,
        offset: 0,
        order: "asc",
        orderby: "userName",
        status: T
      }, y = (P = (m = G == null ? void 0 : G.finalSelected) == null ? void 0 : m.optionSelected) == null ? void 0 : P.id;
      y ? (I.locationId = y, re(y)) : re(null);
      const M = U.find(
        (F) => F.id === _("roleId")
      );
      M != null && M.id ? (I.roleid = M.id, ae(M)) : ae(null), ne(I), Ne(
        Le({
          ...E,
          userFilterPreference: {
            ...I,
            filterRequired: L,
            selectedLocation: G
          }
        })
      ), ce("filter", {
        filter_type: ["location", "role", "status"],
        ...I
      }), D((F) => !F), le();
    } catch (T) {
      Zt({ message: `error : ${T == null ? void 0 : T.message}`, type: "error" }), D((I) => !I);
    }
  };
  return /* @__PURE__ */ l(Xt, { ...ue, children: /* @__PURE__ */ p(
    A,
    {
      className: "m-[1rem]",
      component: "form",
      onSubmit: (m) => {
        if (Object.keys(Q).length > 0) {
          m.preventDefault();
          return;
        }
        B(me)(m);
      },
      "data-testid": "userfilterform-container-grid",
      noValidate: !0,
      children: [
        /* @__PURE__ */ l(Rt, { isLoading: j, children: /* @__PURE__ */ p(A, { className: "flex items-center", children: [
          /* @__PURE__ */ p(Se, { children: [
            u("Location Filter Required"),
            " :"
          ] }),
          /* @__PURE__ */ l(
            Qt,
            {
              defaultChecked: !0,
              checked: L,
              onChange: (m) => {
                se(m.target.checked), m.target.checked || (ie.current = null, xe("level1"));
              }
            }
          )
        ] }) }),
        L === !0 && /* @__PURE__ */ l(qt, { children: /* @__PURE__ */ l(
          pl,
          {
            childForm: !0,
            selectedLocation: G,
            setSelectedLocation: be,
            templateType: "inline",
            disabled: j,
            locations: de,
            setLocations: O,
            fetchAccordingToUserAoi: !!ye.isBahaar
          }
        ) }),
        /* @__PURE__ */ l(Bt, { isLoading: j, children: /* @__PURE__ */ p(A, { children: [
          /* @__PURE__ */ l(Se, { "data-testid": "userfilterform-role-label", children: u("Role") }),
          /* @__PURE__ */ l(
            Ze,
            {
              control: a,
              name: "roleId",
              options: U,
              displayName: "name",
              optionValue: "id",
              errors: Q,
              dataTestId: "userfilterform-role-dropdown",
              className: "mb-[0.3125rem]"
            }
          ),
          /* @__PURE__ */ l(
            Se,
            {
              className: "mt-2",
              "data-testid": "userfilterform-status-label",
              children: u("Status")
            }
          ),
          /* @__PURE__ */ l(
            Ze,
            {
              control: a,
              name: "status",
              defaultValue: "BOTH",
              options: ["ACTIVE", "INACTIVE", "BOTH"],
              errors: Q,
              dataTestId: "userfilterform-status-dropdown"
            }
          ),
          /* @__PURE__ */ p(
            A,
            {
              container: !0,
              spacing: 1,
              marginTop: 1,
              justifyContent: "flex-end",
              "data-testid": "userfilterform-buttons-container",
              children: [
                /* @__PURE__ */ l(A, { item: !0, "data-testid": "userfilterform-closebutton-item", children: /* @__PURE__ */ l(
                  Ae,
                  {
                    variant: "contained",
                    color: "secondary",
                    onClick: () => le(),
                    "data-testid": "userfilterform-close-button",
                    children: u("Close")
                  }
                ) }),
                /* @__PURE__ */ l(A, { item: !0, "data-testid": "userfilterform-searchbutton-item", children: /* @__PURE__ */ l(
                  Ae,
                  {
                    variant: "contained",
                    type: "submit",
                    "data-testid": "userfilterform-search-button",
                    children: u("Search")
                  }
                ) })
              ]
            }
          )
        ] }) })
      ]
    }
  ) });
};
st.propTypes = {
  handleOverlayState: f.any,
  setUsersData: f.any,
  setIsLoading: f.any,
  isLoading: f.any,
  setLocationId: f.func,
  setRoleDetails: f.func,
  roleDetails: f.any,
  status: f.any,
  setStatus: f.any,
  selectedLocation: f.any,
  setSelectedLocation: f.any,
  filterRequired: f.any,
  setFilterRequired: f.any,
  setUserFilterPreference: f.any,
  user: f.any,
  resetLocationDirective: f.any,
  locationIdRef: f.any,
  setSelectedLocationId: f.any,
  locations: f.any,
  setLocations: f.any,
  setAdminRoleIdsStats: f.any
};
function zl() {
  var le, D, j, re, ae, z;
  const q = tl(), Y = at(), [G, be] = n([]), [L, ne] = n([]);
  let E = "#8688ecff", se = "#10b981", ie = "#f43f5e", de = "#f59e0b", O = "#ffffffff";
  const [w, U] = n([]), [J, ce] = n([]), [u, ue] = n(null), [Ne, K] = n(!1), a = ll(), B = a.palette.mode === "dark", [Q, _] = n(0), [v, xe] = n({}), [x, me] = n(null), [m, P] = n(""), [T, I] = n(""), [y, M] = n([]), [F, it] = n(!0), [Ee, dt] = n(!1), [W, ct] = n({
    sortColumn: "userName",
    sortOrder: "asc"
  }), [ut, Oe] = n(!1), _e = 50, { translate: oe } = lt(), [fe, H] = n(!1), [pe, Ue] = n(null), [k, Fe] = n(null), [V, X] = n(null), $ = nt(), $e = ot(), { user: S } = el((e) => e == null ? void 0 : e.Authenticate), [mt, Re] = n(
    ((le = S == null ? void 0 : S.userFilterPreference) == null ? void 0 : le.locationId) || null
  ), Be = Dt(mt), [ft, Pe] = n(
    ((D = $ == null ? void 0 : $.state) == null ? void 0 : D.fromManageUser) === !0 && ((j = S == null ? void 0 : S.userFilterPreference) == null ? void 0 : j.selectedLocation) || {},
    {}
  ), [pt, Me] = n(
    ((re = $ == null ? void 0 : $.state) == null ? void 0 : re.fromManageUser) === !0 && ((ae = S == null ? void 0 : S.userFilterPreference) == null ? void 0 : ae.filterRequired) || !1
  ), [s, Z] = n(
    ((z = $ == null ? void 0 : $.state) == null ? void 0 : z.fromManageUser) === !0 && (S == null ? void 0 : S.userFilterPreference) || {}
  ), [ht, He] = n(0), [gt, Ve] = n([]), vt = jt(() => y == null ? void 0 : y.map((e, r) => {
    let t = "";
    return e != null && e.title && (t += e.title + " "), e != null && e.firstName && (t += e.firstName + " "), e != null && e.lastName && (t += e.lastName), {
      ...e,
      index: r + 1,
      firstName: t.trim()
    };
  }), [y, B]);
  te(() => {
    (async () => {
      var e, r;
      try {
        if (J.length > 0) {
          K(!0);
          const t = await rl({
            code: "GET_USERS_STATS",
            parameters: {
              locationId: (s == null ? void 0 : s.locationId) || pe,
              roleid: (s == null ? void 0 : s.roleid) || (k == null ? void 0 : k.id) || null,
              roleIds: J == null ? void 0 : J.join(",")
            }
          });
          (e = t == null ? void 0 : t.data) != null && e.result && ((r = t == null ? void 0 : t.data) == null ? void 0 : r.result.length) > 0 && ue(t.data.result[0]), K(!1);
        }
      } catch (t) {
        K(!1), console.error("Error fetching user stats:", t);
      }
    })();
  }, [s, J]);
  const Ie = [
    { field: "Sr. No.", label: "#", align: "left" },
    {
      field: "userName",
      label: "User Identity".toUpperCase(),
      sortable: !0,
      sortOrder: "asc",
      align: "left",
      render: (e) => {
        var r;
        return /* @__PURE__ */ p("div", { className: "flex items-center w-48 gap-4 h-full", children: [
          /* @__PURE__ */ l(
            C,
            {
              className: "w-[15%] h-10 rounded-2xl flex items-center justify-center font-black text-xs shadow-sm transition-transform duration-300 group-hover:scale-110",
              sx: {
                background: `linear-gradient(to bottom right, ${N(a.palette.primary.main, 0.05)}, ${N(a.palette.primary.main, 0.2)})`,
                border: `1px solid ${N(a.palette.primary.main, 0.2)}`,
                color: a.palette.primary.main
              },
              children: (r = e == null ? void 0 : e.firstName) == null ? void 0 : r.split(" ").filter((t) => !["Mr", "Ms", "Mrs"].includes(t)).map((t) => t[0]).join("").toUpperCase()
            }
          ),
          /* @__PURE__ */ p("div", { className: "w-[80%] flex flex-col h-full justify-center pt-2", children: [
            /* @__PURE__ */ l(
              C,
              {
                component: "span",
                className: "text-sm font-black leading-tight transition-colors duration-300",
                sx: {
                  color: a.palette.text.primary,
                  // Dynamic text color
                  ".group:hover &": {
                    color: a.palette.primary.main
                  }
                },
                children: e == null ? void 0 : e.firstName
              }
            ),
            /* @__PURE__ */ p(
              C,
              {
                component: "span",
                className: "text-md font-bold font-mono flex items-center gap-1.5 transition-colors duration-300",
                sx: {
                  color: a.palette.text.secondary
                  // Dynamic muted color
                },
                children: [
                  /* @__PURE__ */ l(
                    C,
                    {
                      component: "span",
                      className: "w-1.5 h-1.5 rounded-full transition-colors duration-300",
                      sx: {
                        backgroundColor: a.palette.divider
                        // Dynamic dot color
                      }
                    }
                  ),
                  e == null ? void 0 : e.userName
                ]
              }
            )
          ] })
        ] });
      }
    },
    {
      field: "contactNumber",
      label: "Phone number".toUpperCase(),
      sortable: !0,
      align: "left",
      sortOrder: "asc",
      render: (e) => /* @__PURE__ */ l("div", { className: "flex items-center w-32 gap-4 h-full", children: /* @__PURE__ */ p("div", { className: "flex items-center text-md  tracking-tight", children: [
        /* @__PURE__ */ l(
          C,
          {
            className: "w-7 h-7 rounded-xl flex items-center justify-center mr-2 shadow-sm transition-all duration-300",
            sx: {
              backgroundColor: a.palette.mode === "dark" ? N(a.palette.common.white, 0.05) : "rgb(248, 250, 252)",
              color: a.palette.text.disabled,
              ".group:hover &": {
                backgroundColor: a.palette.primary.main,
                color: "white"
              }
            },
            children: /* @__PURE__ */ l(R, { icon: cl, className: "text-xs" })
          }
        ),
        /* @__PURE__ */ l(
          C,
          {
            component: "span",
            className: "transition-colors duration-300",
            sx: {
              color: a.palette.text.primary,
              ".group:hover &": {
                color: a.palette.primary.main
              }
            },
            children: (e == null ? void 0 : e.contactNumber) || "N/A"
          }
        )
      ] }) })
    },
    {
      field: "roleName",
      label: "Role Name".toUpperCase(),
      sortable: !0,
      sortOrder: "asc",
      align: "left",
      render: (e) => /* @__PURE__ */ l("div", { className: "flex items-center w-auto h-full", children: /* @__PURE__ */ l("div", { className: "flex flex-col gap-1.5", children: /* @__PURE__ */ l(
        C,
        {
          component: "span",
          className: "px-2.5 rounded-lg text-[0.6rem] font-black uppercase tracking-widest w-fit whitespace-nowrap",
          sx: {
            backgroundColor: N(a.palette.primary.main, 0.1),
            color: a.palette.primary.main,
            border: `1px solid ${N(a.palette.primary.main, 0.2)}`
          },
          children: e == null ? void 0 : e.roleName
        }
      ) }) })
    },
    {
      field: "areaOfIntervention",
      label: "Area of Intervention".toUpperCase(),
      align: "left",
      render: (e) => {
        var r;
        const t = (r = e == null ? void 0 : e.areaOfIntervention) == null ? void 0 : r.replace(
          /<br\s*\/?>/gi,
          ", "
        );
        return /* @__PURE__ */ l("div", { className: "flex items-center w-48 h-full", children: /* @__PURE__ */ l("div", { className: "flex flex-col gap-1.5 w-full min-w-0", children: /* @__PURE__ */ l(
          C,
          {
            className: "flex items-center text-md pl-2",
            sx: { color: a.palette.text.primary },
            children: /* @__PURE__ */ l(
              Kt,
              {
                arrow: !0,
                placement: "top",
                title: /* @__PURE__ */ l(
                  "span",
                  {
                    dangerouslySetInnerHTML: {
                      __html: (e == null ? void 0 : e.areaOfIntervention) || "N/A"
                    }
                  }
                ),
                children: /* @__PURE__ */ l(
                  "span",
                  {
                    className: "cursor-default block w-full whitespace-normal break-words",
                    dangerouslySetInnerHTML: {
                      __html: t || "N/A"
                    }
                  }
                )
              }
            )
          }
        ) }) });
      }
    },
    {
      field: "healthFacilityName",
      label: "Health Infrastructure".toUpperCase(),
      align: "left",
      render: (e) => {
        var r;
        return /* @__PURE__ */ p("div", { className: "flex items-center gap-3 h-full", children: [
          /* @__PURE__ */ l(
            C,
            {
              className: "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-300",
              sx: {
                color: a.palette.text.disabled,
                ".group:hover &": {
                  color: a.palette.primary.main,
                  backgroundColor: N(a.palette.primary.main, 0.1)
                }
              },
              children: /* @__PURE__ */ l(R, { icon: ul })
            }
          ),
          /* @__PURE__ */ l(
            C,
            {
              component: "span",
              className: "text-sm  transition-colors duration-300",
              sx: {
                color: a.palette.text.secondary,
                ".group:hover &": {
                  color: a.palette.primary.main
                }
              },
              children: /* @__PURE__ */ l("div", { className: "whitespace-pre-line", children: ((r = e == null ? void 0 : e.healthFacilityName) == null ? void 0 : r.replace(/<br\s*\/?>/gi, `
`)) || "N/A" })
            }
          )
        ] });
      }
    },
    {
      field: "displayState",
      label: "User Status".toUpperCase(),
      align: "left",
      render: (e) => {
        const r = (e == null ? void 0 : e.displayState) === "ACTIVE";
        return /* @__PURE__ */ l("div", { className: "flex items-center justify-center h-full", children: /* @__PURE__ */ p(
          C,
          {
            className: "inline-flex items-center justify-center rounded-full text-[0.8rem] font-black border transition-all duration-500 shadow-sm px-3 w-auto min-w-[110px]",
            sx: {
              backgroundColor: r ? a.palette.mode === "dark" ? N(a.palette.success.main, 0.15) : "rgb(236, 253, 245)" : a.palette.mode === "dark" ? N(a.palette.error.main, 0.15) : "rgb(254, 242, 242)",
              color: r ? a.palette.mode === "dark" ? a.palette.success.light : "rgb(4, 120, 87)" : a.palette.mode === "dark" ? a.palette.error.light : "rgb(248, 113, 113)",
              borderColor: r ? N(a.palette.success.main, 0.3) : N(a.palette.error.main, 0.3)
            },
            children: [
              /* @__PURE__ */ l(
                "span",
                {
                  className: `w-2 h-2 rounded-full mr-2 ${r ? "bg-emerald-500 animate-pulse" : "bg-red-400"}`
                }
              ),
              e == null ? void 0 : e.displayState
            ]
          }
        ) });
      }
    },
    {
      field: "Actions",
      label: "Actions".toUpperCase(),
      align: "left"
    }
  ], [yt, De] = n(Ie);
  te(() => {
    De(Ie);
  }, [B]);
  const bt = async () => {
    var e, r, t, d;
    const i = x.displayState !== "ACTIVE";
    try {
      await Ft(x, { is_active: i }), _(0), Oe((c) => !c), b({
        message: "User State Updated Successfully",
        type: "success"
      });
    } catch (c) {
      _(0), Oe((g) => !g);
      const o = (r = (e = c == null ? void 0 : c.response) == null ? void 0 : e.data) == null ? void 0 : r.errorcode, h = ((d = (t = c == null ? void 0 : c.response) == null ? void 0 : t.data) == null ? void 0 : d.message) || (c == null ? void 0 : c.message) || "Something went wrong";
      console.log(o, h), o === 400 ? b({
        message: `${h}`,
        type: "error"
      }) : b({
        message: "Error in Updating User State.",
        type: "error"
      });
    }
  }, Nt = async () => {
    try {
      const e = await $t({
        userId: ye.isTecho ? x == null ? void 0 : x.userId : x == null ? void 0 : x.id
      });
      e && (M((r) => r.map((t) => (t == null ? void 0 : t.userId) === (ye.isTecho ? x == null ? void 0 : x.userId : x == null ? void 0 : x.id) ? { ...t, loginCode: e.data } : t)), b({
        message: `You have successfully generated your login code. Your login code is : ${e.data}`,
        type: "success"
      }));
    } catch (e) {
      b({ message: `${e.response.data.message}`, type: "error" });
    } finally {
      _(0);
    }
  }, xt = (e) => ye.isTecho ? q(`/ui/medplat/manage/user/${e.userId}`) : q(`/ui/medplat/manage/user/${e.id}`), It = zt(
    (e) => [
      (v == null ? void 0 : v["update.manage.users"]) && {
        label: "",
        icon: /* @__PURE__ */ l(R, { icon: al, "data-testid": "userlist-button-edit" }),
        onClick: () => {
          xt(e);
        },
        iconColor: a.palette.secondary.main,
        backgroundColor: N(a.palette.secondary.main, 0.1),
        hoverBackgroundColor: a.palette.secondary.main,
        hoverIconColor: "white",
        borderColor: a.palette.secondary.main,
        rotateIcon: !0
      },
      {
        label: "",
        icon: /* @__PURE__ */ l(R, { icon: ol, "data-testid": "userlist-button-menu" }),
        iconColor: a.palette.primary.main,
        backgroundColor: N(a.palette.primary.main, 0.1),
        hoverBackgroundColor: a.palette.primary.main,
        hoverIconColor: "white",
        borderColor: a.palette.primary.main,
        menuItems: [
          {
            label: oe(
              e.displayState === "ACTIVE" ? "Mark as Inactive" : "Mark as Active"
            ),
            onClick: () => {
              _(1), me(e);
            }
          },
          e.displayState === "ACTIVE" && !(e != null && e.loginCode) && {
            label: oe("Generate SOH Code"),
            onClick: () => {
              _(2), me(e);
            }
          }
        ].filter(Boolean)
      }
    ].filter(Boolean),
    [v, oe]
  ), Ct = async (e) => {
    const r = e.sortOrder === "asc" ? "desc" : "asc";
    De(
      (t) => t.map((d) => d.field === e.field ? { ...d, sortOrder: r } : d)
    ), ct({ sortColumn: e.field, sortOrder: r });
  }, je = () => {
    Y("button_click", {
      button_name: "User Filter-open-button",
      button_type: "filter_open",
      button_id: "userlist-overlay-filter"
    }), dt(!Ee);
  };
  te(() => {
    const e = setTimeout(() => {
      I(m);
    }, 1e3);
    return () => clearTimeout(e);
  }, [m]);
  async function wt(e, r) {
    var t;
    try {
      if (v != null && v["view.manage.users"]) {
        r && H((i) => !i);
        const d = await Ke({
          limit: e.limit,
          offset: e.offset,
          locationId: (s == null ? void 0 : s.locationId) || pe,
          order: W.sortOrder,
          orderby: W.sortColumn,
          roleIds: w == null ? void 0 : w.join(","),
          status: s != null && s.status ? s == null ? void 0 : s.status : V || "BOTH",
          ...s != null && s.roleid ? { roleid: s == null ? void 0 : s.roleid } : (k == null ? void 0 : k.id) && { roleid: k.id },
          ...m && { searchString: m }
        });
        return m !== "" && Y("search_tracking", {
          searchTerm: m,
          results_count: (t = d == null ? void 0 : d.data) == null ? void 0 : t.length,
          search_type: "Page Search"
        }), r && H((i) => !i), d.data;
      }
    } catch (d) {
      b({ message: `error ${d}`, type: "error" }), H((i) => !i);
    }
  }
  const {
    data: Ce,
    fetchNextPage: Tt,
    hasNextPage: kt
  } = Pt({
    key: [
      "users",
      T,
      W.sortOrder,
      W.sortColumn,
      ut,
      pe,
      k == null ? void 0 : k.id,
      V,
      v,
      w
    ],
    queryFn: ({ pageParam: e }) => {
      const r = !(e != null && e.offset) || (e == null ? void 0 : e.offset) === 0;
      return wt(e, r);
    },
    limit: _e
  });
  te(() => {
    (async () => {
      var e;
      try {
        const { data: r } = await rt({}, { showLoader: !1 }), t = r == null ? void 0 : r.filter((c) => {
          var o, h;
          return (h = (o = c == null ? void 0 : c.name) == null ? void 0 : o.toLowerCase()) == null ? void 0 : h.includes("admin");
        }).map((c) => c.id);
        be(t);
        const d = r == null ? void 0 : r.map((c) => c.id);
        ce(d), H(!0);
        const { data: i } = await Mt("techo.manage.users");
        i && xe(JSON.parse(i)), (e = $ == null ? void 0 : $.state) != null && e.fromManageUser || $e(Le({ ...S, userFilterPreference: {} })), H(!1);
      } catch (r) {
        H(!1), console.error("Error loading initial data:", r);
      }
    })();
  }, []), te(() => {
    var e;
    const r = ((e = Ce == null ? void 0 : Ce.pages) == null ? void 0 : e.flat()) || [];
    it(kt), M(r);
  }, [Ce]);
  const ze = async () => {
    try {
      let e = 0, r = [], t = !0;
      for (; t; ) {
        const d = await Ke({
          limit: 5e4,
          offset: e,
          locationId: (s == null ? void 0 : s.locationId) || pe,
          order: W.sortOrder,
          orderby: W.sortColumn,
          roleIds: w == null ? void 0 : w.join(","),
          status: s != null && s.status ? s == null ? void 0 : s.status : V || "BOTH",
          ...s != null && s.roleid ? { roleid: s == null ? void 0 : s.roleid } : (k == null ? void 0 : k.id) && { roleid: k.id },
          ...m && { searchString: m }
        }), i = (d == null ? void 0 : d.data) || [];
        r = [...r, ...i], i.length < 5e4 ? t = !1 : e += 5e4;
      }
      return r;
    } catch (e) {
      return console.error(e), b({ message: "Error in retriving all Users", type: "error" }), [];
    }
  }, St = async (e) => {
    try {
      const r = /* @__PURE__ */ new Date(), t = r.getMonth() + 1, d = `UserList-${r.getDate()}/${t}/${r.getFullYear().toString().substr(-2)}-${r.getHours()}:${r.getMinutes()}`, i = ee.utils.json_to_sheet(e), c = {
        font: { bold: !0 },
        alignment: { horizontal: "center" }
      };
      if (e.length > 0) {
        const Ge = ee.utils.decode_range(i["!ref"]);
        for (let ke = Ge.s.c; ke <= Ge.e.c; ++ke) {
          const Je = i[ee.utils.encode_cell({ r: 0, c: ke })];
          Je && (Je.s = c);
        }
      }
      const o = ee.utils.book_new();
      ee.utils.book_append_sheet(o, i, "Sheet1");
      const h = ee.write(o, {
        bookType: "xlsx",
        type: "array"
      }), g = new Blob([h], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      }), he = (g.size / (1024 * 1024)).toFixed(2);
      ml.saveAs(g, `${d}.xlsx`), Y("file_download", {
        file_type: "excel",
        file_name: `${d}.xlsx`,
        file_size: `${he} MB`,
        filter_parameters: {
          taskTypeId: y.id
        },
        download_status: "success"
      });
    } catch (r) {
      console.error("Error generating Excel file:", r), b({ message: "Error generating Excel file", type: "error" });
    }
  }, [qe, we] = n(!1), At = async () => {
    try {
      we(!0);
      let e;
      (L == null ? void 0 : L.length) === 0 ? (e = await ze(), ne(e)) : e = L;
      let r = [];
      e && e.length > 0 && (r = e.map((t, d) => {
        var i;
        let c = "", o;
        t != null && t.title && (c += t.title + " "), t != null && t.firstName && (c += t.firstName + " "), t != null && t.lastName && (c += t.lastName), t != null && t.areaOfIntervention && (o = (i = t == null ? void 0 : t.areaOfIntervention) == null ? void 0 : i.replace(
          /<br\s*\/?>/gi,
          `,
`
        ));
        const h = {
          "No.": d + 1,
          NAME: c || "NA",
          "USER IDENTITY": (t == null ? void 0 : t.userName) || "NA",
          "MOBILE NUMBER": (t == null ? void 0 : t.contactNumber) || "NA",
          "USER ROLE": (t == null ? void 0 : t.roleName) || "NA",
          "AREA OF INTERVENTION": o || "NA",
          "HEALTH INFRASTRUCTURE": (t == null ? void 0 : t.healthFacilityName) || "NA",
          "USER STATUS": (t == null ? void 0 : t.displayState) || "NA"
        };
        return Object.keys(h).forEach((g) => {
          g === "id" ? delete h[g] : h[g] === null ? h[g] = "" : typeof h[g] == "boolean" && (h[g] = h[g] ? "Yes" : "No");
        }), h;
      })), St(r), we(!1);
    } catch (e) {
      we(!1), console.log(e), b({
        message: "Error in downloading excel",
        type: "error"
      });
    }
  }, Lt = fl(), [Ye, Te] = n(!1), Et = async () => {
    try {
      Te(!0);
      let e = [];
      if ((L == null ? void 0 : L.length) === 0 ? (e = await ze(), ne(e)) : e = L, !e || e.length === 0) return;
      let r = [], t = [];
      r.push("NAME"), t.push("name"), Ie.filter(
        (o) => o.field !== "Actions" && o.field !== "index" && o.field !== "Sr. No."
      ).forEach((o) => {
        r.push(o.label), t.push(o.field);
      });
      let d = e.map((o) => {
        var h;
        let g = "", he;
        return o != null && o.title && (g += o.title + " "), o != null && o.firstName && (g += o.firstName + " "), o != null && o.lastName && (g += o.lastName), o != null && o.areaOfIntervention && (he = (h = o == null ? void 0 : o.areaOfIntervention) == null ? void 0 : h.replace(
          /<br\s*\/?>/gi,
          `,
`
        )), {
          ...o,
          name: g || "NA",
          areaOfIntervention: he
        };
      });
      const i = /* @__PURE__ */ new Date(), c = i.getMonth() + 1;
      Lt({
        columns: r,
        keys: t,
        data: d,
        fileName: `UserList-${i.getDate()}/${c}/${i.getFullYear().toString().substr(-2)}-${i.getHours()}:${i.getMinutes()}`,
        headerText: "User List",
        footerText: "User List",
        orientation: r.length > 7 ? "landscape" : "portrait"
      }), Te(!1);
    } catch (e) {
      Te(!1), console.error(e);
    }
  }, Ot = () => {
    Ue(null), Fe(null), X("BOTH"), Z({}), Me(!1), Ve([]), U([]), $e(Le({ ...S, userFilterPreference: {} })), Re(null), Pe({}), He((e) => e + 1), Be.current = null, je();
  };
  return !fe && !(v != null && v["view.manage.users"]) ? /* @__PURE__ */ l(C, { className: "flex justify-center items-center w-full h-[80vh]", children: /* @__PURE__ */ l(
    Gt,
    {
      className: "h-80 w-150 flex justify-center items-center",
      "data-testid": "userlist-no-permission",
      children: /* @__PURE__ */ l(We, { variant: "h5", className: "text-customBlue", children: "You dont have permission to view Users" })
    }
  ) }) : /* @__PURE__ */ p(A, { className: "w-[98%] mt-4 ", children: [
    /* @__PURE__ */ l(
      Qe,
      {
        open: Q === 1,
        handleClose: () => _(0),
        handleClick: bt,
        title: "CONFIRM ACTION",
        description: "Are you sure you want toggle the state of this user type?",
        dataTestId: "userlist-modal-status-confirmation"
      }
    ),
    /* @__PURE__ */ l(
      Qe,
      {
        open: Q === 2,
        handleClose: () => _(0),
        handleClick: Nt,
        title: "CONFIRM ACTION",
        description: "Are you sure you want to Generate SOH code ?",
        dataTestId: "userlist-modal-generate-soh-confirmation"
      }
    ),
    /* @__PURE__ */ l(_t, { isLoading: fe, children: /* @__PURE__ */ p(
      A,
      {
        container: !0,
        className: "flex flex-col md:flex-row mb-2 justify-between items-start md:items-center space-y-2 md:space-y-0",
        children: [
          /* @__PURE__ */ l(A, { children: /* @__PURE__ */ l(
            We,
            {
              variant: "body2",
              className: "font-bold font-sans text-lg text-[var(--color-customBlue)] uppercase text-customBlue",
              "data-testid": "notification-list-typography-title",
              children: oe("User List")
            }
          ) }),
          /* @__PURE__ */ p(A, { className: "flex flex-col md:flex-row w-full md:w-auto space-y-2 md:space-y-0 md:space-x-3", children: [
            /* @__PURE__ */ l(A, { className: "w-full md:w-auto", children: /* @__PURE__ */ l(
              Jt,
              {
                name: "searchQuery",
                id: "searchQuery",
                className: "w-full md:w-auto",
                placeholder: "Search...",
                size: "small",
                onChange: (e) => {
                  var r;
                  return P((r = e.target) == null ? void 0 : r.value);
                },
                value: m,
                "data-testid": "userlist-textfield-search",
                sx: {
                  "& .MuiInputBase-root": {
                    backgroundColor: (e) => e.palette.background.paper
                  }
                }
              }
            ) }),
            /* @__PURE__ */ p("div", { className: "flex items-center gap-3 flex-wrap md:flex-nowrap", children: [
              /* @__PURE__ */ p(
                "div",
                {
                  className: `flex items-center rounded-2xl p-1 shadow-sm transition-all duration-300 border ${B ? "bg-slate-900 border-slate-800" : "bg-white border-slate-200"}`,
                  children: [
                    /* @__PURE__ */ l(
                      "button",
                      {
                        disabled: Ye,
                        onClick: Et,
                        className: `px-4 py-2 rounded-xl transition-all flex items-center gap-2 text-xs font-black uppercase tracking-wider ${B ? "text-slate-400 hover:text-slate-100 hover:bg-slate-800" : "text-slate-600 hover:text-red-600 hover:bg-slate-50"}`,
                        children: Ye ? /* @__PURE__ */ p(ge, { children: [
                          /* @__PURE__ */ l(Xe, { size: 14, sx: { color: "inherit" } }),
                          /* @__PURE__ */ l(R, { icon: et, className: "mr-1" }),
                          "Pdf"
                        ] }) : /* @__PURE__ */ p(ge, { children: [
                          /* @__PURE__ */ l(R, { icon: et, className: "mr-1" }),
                          "Pdf"
                        ] })
                      }
                    ),
                    /* @__PURE__ */ l(
                      "button",
                      {
                        disabled: qe,
                        onClick: () => At(),
                        className: `px-4 py-2 rounded-xl transition-all flex items-center gap-2 text-xs font-black uppercase tracking-wider ml-1 ${B ? "bg-slate-800 text-slate-100 hover:bg-slate-700" : "bg-[#243A50] text-white hover:bg-[#1a2b3c]"}`,
                        children: qe ? /* @__PURE__ */ p(ge, { children: [
                          /* @__PURE__ */ l(Xe, { size: 14, sx: { color: "inherit" } }),
                          /* @__PURE__ */ l(R, { icon: tt, className: "mr-1" }),
                          "Excel Data"
                        ] }) : /* @__PURE__ */ p(ge, { children: [
                          /* @__PURE__ */ l(R, { icon: tt, className: "mr-1" }),
                          "Excel Data"
                        ] })
                      }
                    )
                  ]
                }
              ),
              (v == null ? void 0 : v["create.manage.users"]) && /* @__PURE__ */ l(
                Ae,
                {
                  variant: "contained",
                  className: "w-auto ml-auto",
                  onClick: () => {
                    Y("button_click", {
                      button_name: "add_user",
                      button_type: "navigate",
                      button_id: "userlist-button-add"
                    }), q("/ui/medplat/manage/user");
                  },
                  size: "small",
                  "data-testid": "userlist-button-add",
                  children: oe("Add")
                }
              )
            ] })
          ] })
        ]
      }
    ) }),
    /* @__PURE__ */ l(Ut, { isLoading: Ne, children: u && /* @__PURE__ */ p("div", { className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mt-4 mb-4", children: [
      /* @__PURE__ */ l(
        ve,
        {
          title: "Total Users",
          value: (u == null ? void 0 : u.total_users) || 0,
          icon: nl,
          bottomIndicator: E,
          selected: V === "BOTH" && w.length === 0,
          selectedBgColor: E,
          selectedTitleColor: O,
          selectedValueColor: O,
          onClick: () => {
            (u == null ? void 0 : u.total_users) > 0 ? (U([]), X("BOTH"), Z((e) => ({
              ...e,
              status: "BOTH"
            }))) : b({ message: "No users found", type: "warning" });
          }
        }
      ),
      /* @__PURE__ */ l(
        ve,
        {
          title: "Active Users",
          value: (u == null ? void 0 : u.active_count) || 0,
          icon: sl,
          bottomIndicator: se,
          selected: V === "ACTIVE" && w.length === 0,
          selectedBgColor: se,
          selectedTitleColor: O,
          selectedValueColor: O,
          onClick: () => {
            (u == null ? void 0 : u.active_count) > 0 ? (U([]), X("ACTIVE"), Z((e) => ({
              ...e,
              status: "ACTIVE"
            }))) : b({
              message: "No active users found",
              type: "warning"
            });
          }
        }
      ),
      /* @__PURE__ */ l(
        ve,
        {
          title: "Inactive Users",
          value: (u == null ? void 0 : u.inactive_count) || 0,
          icon: il,
          bottomIndicator: ie,
          selected: V === "INACTIVE" && w.length === 0,
          selectedBgColor: ie,
          selectedTitleColor: O,
          selectedValueColor: O,
          onClick: () => {
            (u == null ? void 0 : u.inactive_count) > 0 ? (U([]), X("INACTIVE"), Z((e) => ({
              ...e,
              status: "INACTIVE"
            }))) : b({
              message: "No inactive users found",
              type: "warning"
            });
          }
        }
      ),
      /* @__PURE__ */ l(
        ve,
        {
          title: "Admins",
          value: (u == null ? void 0 : u.admin_role_count) || 0,
          icon: dl,
          bottomIndicator: de,
          selected: w.length > 0,
          selectedBgColor: de,
          selectedTitleColor: O,
          selectedValueColor: O,
          onClick: () => {
            (u == null ? void 0 : u.admin_role_count) > 0 ? (X("BOTH"), Z((e) => ({
              ...e,
              status: "BOTH"
            })), U(G)) : b({
              message: "No active users found",
              type: "warning"
            });
          }
        }
      )
    ] }) }),
    /* @__PURE__ */ l(
      Ht,
      {
        columns: yt,
        tableData: vt,
        actions: It,
        paginationConfig: {
          pagination: !0,
          paginationType: "infinite-scroll",
          rowsPerPageInTable: _e,
          hasMore: F,
          loadMore: () => F && Tt({ cancelRefetch: !1 })
        },
        styleConfig: { cellStyle: { maxLines: 2 } },
        isLoading: y ? fe : !0,
        handleSort: Ct,
        dataTestId: "userlist-table-customized"
      }
    ),
    /* @__PURE__ */ l(
      Vt,
      {
        title: "User Filter",
        resetButtonLabel: "Reset",
        onResetClick: Ot,
        FormBody: st,
        handleOverlayState: je,
        overlayOpen: Ee,
        dataTestId: "userlist-overlay-filter",
        formProps: {
          setAdminRoleIdsStats: U,
          setIsLoading: H,
          isLoading: fe,
          setLocationId: Ue,
          setRoleDetails: Fe,
          roleDetails: k,
          status: V,
          setStatus: X,
          setSelectedLocation: Pe,
          selectedLocation: ft,
          filterRequired: pt,
          setFilterRequired: Me,
          setUserFilterPreference: Z,
          user: S,
          userFilterPreference: s,
          locationIdRef: Be,
          setSelectedLocationId: Re,
          resetLocationDirective: ht,
          setResetLocationDirective: He,
          locations: gt,
          setLocations: Ve
        }
      }
    )
  ] });
}
export {
  zl as default
};
//# sourceMappingURL=UserList-S5Q76wO7-Cj5u_K4_.js.map
