import { jsxs as d, jsx as t, Fragment as Ae } from "react/jsx-runtime";
import { useState as s, useRef as De, useEffect as p, Suspense as _, lazy as k } from "react";
import { useTranslateProvider as Pe } from "@/common/languageTranslator/TranslationContext";
import { api as G } from "@/common/interceptors/AxiosInterceptor";
import { execute as N } from "@/common/services/GlobalApis";
import Oe from "@/common/syncWithServer/SyncWithServerDialog";
import { showToast as g } from "@/common/toaster/toaster";
import Re from "@/hooks/usePagination";
import Fe from "@/views/custom-components/CustomConfirmationModal";
import { Box as Be, Card as He, Typography as J, TextField as ze, Button as Le } from "@mui/material";
import u from "@mui/material/Grid2";
import Me from "@/hooks/useTrackEvent";
import je from "@/views/custom-components/CustomizedTable/CustomizedTableV2";
import { FontAwesomeIcon as Y } from "@fortawesome/react-fontawesome";
import { faBars as Ue, faPen as Ve } from "@fortawesome/free-solid-svg-icons";
import W from "prop-types";
import { useSelector as Je } from "react-redux";
import { getUseSkeleton as Ye } from "@/store/reducers/SkeletonReducer";
import { getAssignedFeatures as We } from "@/utils/feature";
import $ from "@/common/services/util/GeneralUtil";
import './QueryBuilder.css';const $e = (l) => G.put("/resource", l), vt = (l) => G.post("/resource", l), K = ({ children: l, isLoading: b }) => !Je(Ye) || !b ? l : /* @__PURE__ */ d("div", { className: "flex flex-col gap-2", children: [
  /* @__PURE__ */ d("div", { className: "w-full justify-between flex-wrap flex flex-row pt-6", children: [
    /* @__PURE__ */ t("div", { children: /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm h-[36px] w-[64px]" }) }),
    /* @__PURE__ */ d("div", { className: "flex", children: [
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm h-[32px] w-[160px] mr-2" }),
      /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm h-[32px] w-[60px]" })
    ] })
  ] }),
  /* @__PURE__ */ t("div", { className: "bg-gray-300 animate-pulse rounded-sm w-full h-100" })
] });
K.propTypes = {
  children: W.any,
  isLoading: W.any
};
const Ge = k(() => import("./AddEditQueryBuilder-Bcjl5mXE.js")), Ke = k(() => import("./ShowFlywayQuery-BkyA6QaA.js")), Xe = k(() => import("./ShowQueryHistory-BDN0tzHg.js")), Ze = () => {
  var V;
  const l = Me(), [b, E] = s([]), [X, Z] = s(!1), [A, ee] = s([]), [m, D] = s(1), [te, re] = s(""), [se, oe] = s(""), [ae, ne] = s({}), [ie, P] = s(!1), [le, ce] = s(""), [ue, O] = s(!1), [R, w] = s(null), [c, F] = s(null), [B, de] = s(null), [n, ye] = s({}), [he, H] = s(!1), [fe, z] = s({}), [me, v] = s(!1), [L, M] = s(!1), [pe, ge] = s(0), { translate: S } = Pe(), [i, be] = s({}), C = De(i);
  p(() => {
    C.current = i;
  }, [i]);
  const we = $.isEkavach || $.isPhmp, T = [
    { field: "code", label: "Code", align: "left" },
    {
      field: "description",
      label: "Description",
      align: "left"
    },
    { field: "query", label: "Query", align: "left" },
    { field: "returnsResultSet", label: "Returns Result Set" },
    { field: "isPublic", label: "Is Public" }
  ];
  we && T.push({
    field: "isClickhouseQuery",
    label: "Is Clickhouse Query"
  }), T.push({ field: "Actions", label: "Actions" });
  const [q, y] = s(!1), h = 50, { data: j } = Re({
    key: ["queries", B, m, X, i],
    queryFn: (e) => Q(e),
    currentPage: m,
    limit: h,
    searchString: B || null,
    paginationType: "traditional"
  }), ve = (e) => {
    const r = A.filter((o) => o.uuid === e.uuid);
    z(r[0]), M((o) => !o), H(!0);
  }, Se = (e) => {
    re(
      (e == null ? void 0 : e.state) === "ACTIVE" ? "Mark as Inactive" : "Mark as Active"
    ), oe(
      (e == null ? void 0 : e.state) === "ACTIVE" ? "Are you sure you want to change the state from active to inactive?" : "Are you sure you want to change the state from inactive to active?"
    );
    const r = A.filter((o) => o.uuid === e.uuid);
    ye(r[0]);
  }, Ce = async () => {
    v((e) => !e);
  }, Te = async () => {
    try {
      let e = JSON.parse(JSON.stringify(n));
      e.state = (n == null ? void 0 : n.state) === "ACTIVE" ? "INACTIVE" : "ACTIVE", await $e(e), await I();
      const r = await Q({
        limit: h,
        offset: (m - 1) * h,
        searchString: c || ""
      });
      x(r), Z(n), v((o) => !o);
    } catch (e) {
      console.error(e), g({ message: "Error in toggle state", type: "error" });
    }
  }, qe = async () => {
    var e, r, o;
    try {
      const a = {
        code: "retrieve_logged_actions_by_table_name_query_code",
        parameters: {
          tableName: "query_master",
          queryCode: n.code
        }
      }, f = await N(a);
      ((r = (e = f == null ? void 0 : f.data) == null ? void 0 : e.result) == null ? void 0 : r.length) === 0 ? g({
        message: "No Query History found for Query code",
        type: "warn"
      }) : (ne((o = f == null ? void 0 : f.data) == null ? void 0 : o.result), P((Ee) => !Ee));
    } catch (a) {
      console.error(a), g({ message: "Error in loading Query History", type: "error" });
    }
  }, Ie = () => {
    ce(n), O((e) => !e);
  }, Qe = () => {
    w(n == null ? void 0 : n.uuid);
  }, xe = () => w(() => null), _e = () => {
    var r;
    const e = [
      {
        label: "",
        icon: /* @__PURE__ */ t(Y, { icon: Ue, size: "lg" }),
        menuClick: Se,
        menuItems: [
          {
            label: S(te),
            onClick: Ce
          },
          {
            label: "Show Flyway Query",
            onClick: Ie
          },
          {
            label: "Show Query History",
            onClick: qe
          },
          {
            label: "Sync With Server",
            onClick: Qe
          }
        ],
        dataTestId: "MenuIcon"
      }
    ];
    return (r = C.current) != null && r["update.admin.query"] && e.unshift({
      label: "",
      icon: /* @__PURE__ */ t(Y, { icon: Ve, size: "lg" }),
      onClick: ve,
      dataTestId: "EditIcon"
    }), e;
  };
  p(() => {
    const e = setTimeout(async () => {
      await I(), D(1), de(c);
    }, 1e3);
    return () => clearTimeout(e);
  }, [c]);
  const I = async () => {
    try {
      const { data: e } = await N(
        {
          code: "fetch_total_count_for_query_builder",
          parameters: {
            state: null,
            searchString: c || null
          }
        },
        { showLoader: !1 }
      );
      ge(e.result[0].count);
    } catch (e) {
      console.error(e);
    }
  }, Q = async (e) => {
    try {
      if (i != null && i["view.admin.query"]) {
        y((o) => !o);
        const { data: r } = await N(
          {
            code: "fetch_queries_for_query_builder",
            parameters: {
              limit: e.limit || 50,
              offset: e.offset || 0,
              state: null,
              searchString: e.searchString || ""
            }
          },
          { showLoader: !1 }
        );
        return c !== "" && l("search_tracking", {
          searchTerm: c,
          results_count: r == null ? void 0 : r.length,
          search_type: "Page Search"
        }), y((o) => !o), r.result;
      }
    } catch (r) {
      g({ message: `error ${r}`, type: "error" }), y((o) => !o);
    }
  }, Ne = async () => {
    try {
      y(!0);
      const { data: e } = await We("techo.manage.query");
      be(JSON.parse(e)), y(!1);
    } catch (e) {
      console.error("Error loading rights:", e), y(!1);
    }
  };
  p(() => {
    Ne();
  }, []);
  const x = (e) => {
    const r = (e == null ? void 0 : e.flat()) || [];
    ee(r);
    const o = r.map((a) => ({
      ...a,
      query: `${a == null ? void 0 : a.query.slice(0, 50)}...`,
      returnsResultSet: a != null && a.returnsResultSet ? "Yes" : "No",
      isPublic: a != null && a.isPublic ? "Yes" : "No",
      isClickhouseQuery: a != null && a.isClickhouseQuery ? "Yes" : "No"
    }));
    E(o);
  };
  p(() => {
    x(j);
  }, [j]);
  const U = () => {
    l("button_click", {
      button_name: "querybuilder-add-button",
      button_type: "navigate",
      button_id: "querybuilder-add-button"
    }), M((e) => !e), H(!1), z({});
  }, ke = async () => {
    try {
      if (c !== "")
        F("");
      else {
        await I();
        const e = await Q({
          limit: h,
          offset: (m - 1) * h,
          searchString: c || ""
        });
        x(e);
      }
    } catch (e) {
      console.error(e);
    }
  };
  return !q && !((V = C.current) != null && V["view.admin.query"]) ? /* @__PURE__ */ t(Be, { className: "flex justify-center items-center w-full h-[80vh]", children: /* @__PURE__ */ t(He, { className: "h-80 w-150 flex justify-center items-center", children: /* @__PURE__ */ t(J, { variant: "h5", "data-testid": "no-permission-message", className: "text-customBlue", children: "You dont have permission to view Queries" }) }) }) : /* @__PURE__ */ d(u, { pt: 2, sx: { height: "calc(100vh - 84px)" }, children: [
    /* @__PURE__ */ t(_, { children: L && /* @__PURE__ */ t(
      Ge,
      {
        loadInitialState: ke,
        isEditMode: he,
        editRow: fe,
        open: L,
        close: U,
        "data-testid": "querybuilder-addeditquerybuilder"
      }
    ) }),
    R && /* @__PURE__ */ t(
      Oe,
      {
        isOpen: !!w,
        handleClose: xe,
        featureUUID: R,
        dataTestId: "querybuilder-syncwithserverdialog"
      }
    ),
    /* @__PURE__ */ t(_, { children: /* @__PURE__ */ t(
      Ke,
      {
        configuredQuery: le,
        open: ue,
        onClose: () => {
          O((e) => !e);
        },
        "data-testid": "querybuilder-showflywayquery"
      }
    ) }),
    /* @__PURE__ */ t(_, { children: /* @__PURE__ */ t(
      Xe,
      {
        historyList: ae,
        open: ie,
        handleClose: () => {
          P((e) => !e);
        },
        "data-testid": "querybuilder-showqueryhistory"
      }
    ) }),
    /* @__PURE__ */ t(
      Fe,
      {
        description: se,
        title: "CONFIRM ACTION",
        handleClick: Te,
        open: me,
        handleClose: () => v((e) => !e),
        dataTestId: "querybuilder-customconfirmationmodal"
      }
    ),
    /* @__PURE__ */ t(u, { children: /* @__PURE__ */ t(K, { isLoading: q, children: /* @__PURE__ */ d(Ae, { children: [
      /* @__PURE__ */ d(
        u,
        {
          container: !0,
          direction: "row",
          justifyContent: "space-between",
          alignItems: "center",
          children: [
            /* @__PURE__ */ t(u, { item: "true", mt: 1, children: /* @__PURE__ */ t(
              J,
              {
                variant: "body2",
                className: "font-bold font-sans  text-lg uppercase text-customBlue",
                children: S("Queries")
              }
            ) }),
            /* @__PURE__ */ t(u, { item: "true", children: /* @__PURE__ */ d(u, { container: !0, spacing: 2, children: [
              /* @__PURE__ */ t(u, { item: "true", children: /* @__PURE__ */ t(
                ze,
                {
                  name: "searchQuery",
                  id: "searchQuery",
                  className: "m-0 p-0",
                  placeholder: "Search Code",
                  size: "small",
                  value: c,
                  onChange: (e) => {
                    var r;
                    return F((r = e == null ? void 0 : e.target) == null ? void 0 : r.value);
                  },
                  slotProps: {
                    input: {
                      className: "custom-input-root"
                    }
                  },
                  sx: {
                    "& .MuiInputBase-root": {
                      backgroundColor: (e) => e.palette.background.paper
                    }
                  },
                  "data-testid": "querybuilder-search-textfield"
                }
              ) }),
              (i == null ? void 0 : i["create.admin.query"]) && /* @__PURE__ */ t(u, { item: "true", className: "flex items-center", children: /* @__PURE__ */ t(
                Le,
                {
                  size: "small",
                  variant: "contained",
                  onClick: U,
                  "data-testid": "querybuilder-add-button",
                  children: S("Add")
                }
              ) })
            ] }) })
          ]
        }
      ),
      /* @__PURE__ */ t(u, { container: !0, className: "mt-4", children: /* @__PURE__ */ t(
        je,
        {
          columns: T,
          tableData: b,
          actions: _e(),
          paginationConfig: {
            pagination: !0,
            rowsPerPageInTable: h,
            onPageChange: (e) => {
              D(e);
            },
            currentPage: m,
            totalRows: pe
          },
          dataTestId: "querybuilder-customizedtable",
          styleConfig: { tableStyle: { maxHeight: 65 } },
          isLoading: q
        }
      ) })
    ] }) }) })
  ] });
}, St = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Ze
}, Symbol.toStringTag, { value: "Module" }));
export {
  St as Q,
  vt as s
};
//# sourceMappingURL=QueryBuilder-DXexUIe8.js.map
