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