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