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