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