import { jsxs as w, jsx as i, Fragment as Z } from "react/jsx-runtime";
import { useState as n, useEffect as D, useCallback as ee } from "react";
import { TextField as B, Button as x, Dialog as te, DialogTitle as ae, DialogContent as oe, DialogActions as ie } from "@mui/material";
import { showToast as p } from "@/common/toaster/toaster";
import { execute as q } from "@/common/services/GlobalApis";
import k from "@mui/material/Grid2";
import { useNavigate as ne } from "react-router";
import { f as re, i as le } from "./ImmunizationSkeleton-D2tdv5k--B7SY-gnr.js";
import L from "prop-types";
import P from "@/views/custom-components/CustomConfirmationModal";
import se from "@/hooks/useTrackEvent";
import { useTranslateProvider as de } from "@/common/languageTranslator/TranslationContext";
import ce from "@/views/custom-components/CustomizedTable/CustomizedTableV2";
import { FontAwesomeIcon as U } from "@fortawesome/react-fontawesome";
import { faPen as ue, faTrash as me } from "@fortawesome/free-solid-svg-icons";
import { getAssignedFeatures as ye } from "@/utils/feature";
const Q = ({ configuredQuery: f, open: z, onClose: g, dataTestId: E }) => {
  const [b, C] = n(""), { translate: u } = de(), [F, m] = n(!1), O = ee(() => {
    let a = JSON.parse(JSON.stringify(f));
    if (a.forEach((r) => {
      delete r.id, delete r.created_at, delete r.updated_at;
    }), !Array.isArray(a) || a.length === 0) {
      p({ message: "No data to generate", type: "error" });
      return;
    }
    const s = Object.keys(a[0]), h = a.map((r) => `(${s.map((A) => {
      const y = r[A];
      return typeof y == "string" ? `'${y.replace(/'/g, "''")}'` : y == null ? "NULL" : typeof y == "boolean" ? y ? "TRUE" : "FALSE" : y;
    }).join(", ")})`).join(`,
`), l = `${s.filter((r) => r !== "code").map((r) => `${r} = EXCLUDED.${r}`).join(", ")}, updated_at = CURRENT_TIMESTAMP`, N = `INSERT INTO rch_immunization_configuration (${s.join(", ")}) 
VALUES
${h}
ON CONFLICT (code) DO UPDATE SET
${l};
          `;
    C(N);
  }, [f]), v = () => {
    var a;
    (a = navigator == null ? void 0 : navigator.clipboard) == null || a.writeText(b).then(() => {
      p({ message: "Query Copied", type: "success" }), g();
    });
  }, $ = () => {
    T(), m((a) => !a);
  }, _ = se(), T = () => {
    const a = new Blob([b], { type: "text/plain" }), s = (a.size / 1024).toFixed(2), h = URL.createObjectURL(a), l = document.createElement("a");
    l.href = h, l.download = `V${(/* @__PURE__ */ new Date()).getTime()}__CHANGE_IN_IMMUNIZATION_TABLE}.sql`, document.body.appendChild(l), l.click(), _("file_download", {
      file_type: "sql",
      file_name: l.download,
      file_size: `${s} KB`,
      download_status: "success"
    }), document.body.removeChild(l), URL.revokeObjectURL(h), p({ message: "Query Downloaded SuccessFully", type: "success" }), g();
  }, I = () => {
    T();
  };
  return D(() => {
    f && O();
  }, [f]), /* @__PURE__ */ w(Z, { children: [
    /* @__PURE__ */ i(
      P,
      {
        description: "This Flyway contains keyword 'public'. Are you sure you want to download?",
        title: "CONFIRM ACTION",
        handleClick: $,
        open: F,
        handleClose: () => m((a) => !a),
        dataTestId: "showflywayquery-customconfirmationmodal-confirmation-modal"
      }
    ),
    /* @__PURE__ */ w(te, { open: z, onClose: g, fullWidth: !0, maxWidth: "md", "data-testid": E, children: [
      /* @__PURE__ */ i(ae, { className: "p-2.5 px-5 flex border-b font-medium text-lg", children: u("Flyway Query") }),
      /* @__PURE__ */ i(oe, { children: /* @__PURE__ */ i(
        B,
        {
          multiline: !0,
          rows: 10,
          variant: "outlined",
          fullWidth: !0,
          value: b,
          sx: {
            "& .MuiInputBase-input": {
              fontSize: "14px"
            },
            "& .MuiOutlinedInput-root": {
              borderRadius: "5px"
            }
          },
          slotProps: {
            input: {
              readOnly: !0
            }
          },
          "data-testid": "showflywayquery-textfield-query-display"
        }
      ) }),
      /* @__PURE__ */ w(ie, { children: [
        /* @__PURE__ */ i(
          x,
          {
            onClick: I,
            variant: "contained",
            size: "small",
            color: "primary",
            "data-testid": "showflywayquery-button-download-action",
            children: u("Download")
          }
        ),
        /* @__PURE__ */ i(
          x,
          {
            onClick: v,
            variant: "contained",
            size: "small",
            color: "primary",
            "data-testid": "showflywayquery-button-copyquery-action",
            children: u("Copy Query")
          }
        ),
        /* @__PURE__ */ i(
          x,
          {
            onClick: g,
            variant: "contained",
            color: "secondary",
            size: "small",
            "data-testid": "showflywayquery-button-cancel-action",
            children: u("Cancel")
          }
        )
      ] })
    ] })
  ] });
};
Q.propTypes = {
  configuredQuery: L.any,
  open: L.any,
  onClose: L.any,
  dataTestId: L.any
};
const Le = () => {
  const f = ne(), { t: z } = re(), [g, E] = n([]), [b, C] = n([]), [u, F] = n([]), [m, O] = n(""), [v, $] = n(!1), [_, T] = n(!1), [I, a] = n([]), [s, h] = n([]), [l, N] = n(!1), [r, A] = n(!1), [y, J] = n({}), [j, G] = n({});
  D(() => {
    h(() => g.filter(
      (e) => I.some((t) => t.id === e.id)
    ));
  }, [I]);
  const H = [
    { field: "Sr. No.", label: "#", align: "left" },
    // { field: 'code', label: 'Code', align: 'left', isBold: true },
    { field: "name", label: "Name", align: "left" },
    { field: "fromAgeDays", label: "Eligible From" },
    { field: "toAgeDays", label: "Eligible To" },
    { field: "base_date", label: "Base Date" },
    { field: "Actions", label: "Actions" }
  ], W = [
    {
      label: "Fill Form",
      icon: /* @__PURE__ */ i(U, { icon: ue }),
      onClick: (e) => {
        f(`/ui/medplat/manage/manageImmunization/${e == null ? void 0 : e.id}`);
      }
    },
    {
      label: "",
      icon: /* @__PURE__ */ i(U, { icon: me }),
      onClick: (e) => {
        A(!0), J(e);
      }
    }
  ];
  D(() => {
    M();
  }, []);
  const V = (e) => {
    const t = JSON.parse(e);
    return t.dependencies && t.dependencies.length > 0 ? t.dependencies[0].message : "NA";
  }, R = (e) => {
    if (typeof e != "number" || e <= 0) return "-";
    const t = Math.floor(e / 365), d = e % 365, c = Math.floor(d / 30), S = d % 30, o = [];
    return t > 0 && o.push(`${t} ${t === 1 ? "year" : "years"}`), c > 0 && o.push(`${c} ${c === 1 ? "month" : "months"}`), (S > 0 || t === 0 && c === 0) && o.push(`${S} ${S === 1 ? "day" : "days"}`), o.join(" ") || "0 days";
  }, M = async () => {
    var e, t;
    try {
      N((o) => !o);
      const d = await q({
        code: "get_immunization_detail",
        parameters: {}
      });
      E((e = d == null ? void 0 : d.data) == null ? void 0 : e.result);
      const c = (t = d == null ? void 0 : d.data) == null ? void 0 : t.result.filter((o) => o.is_active === !0).map((o) => ({
        ...o,
        fromAgeDays: R(o.from_age_days),
        toAgeDays: R(o.to_age_days),
        validationMessage: o.validations ? V(o.validations) : "NA"
      })), { data: S } = await ye(
        "techo.manage.immunizationConfiguratorList"
      );
      G(JSON.parse(S)), C(c), F(c), N((o) => !o);
    } catch (d) {
      console.error(d), p({ message: "Error in loading immunization", type: "error" }), N((c) => !c);
    }
  }, K = (e) => {
    O(e.target.value);
  };
  D(() => {
    if (!m) {
      C(u);
      return;
    }
    const e = u.filter(
      (t) => t.code.toLowerCase().includes(m.toLowerCase()) || t.name.toLowerCase().includes(m.toLowerCase())
    );
    C(e);
  }, [m, u]);
  const X = () => {
    (s == null ? void 0 : s.length) > 0 ? T(!0) : p({ message: "Select atleast one row", type: "info" });
  }, Y = async (e) => {
    try {
      let t = {
        id: parseInt(e.id),
        code: e.code,
        name: e.name,
        isrecursive: e.is_recursive || !1,
        fromAgeDays: e.from_age_days,
        toAgeDays: e.to_age_days,
        basedate: e.base_date,
        validations: e.validations,
        recursiveobject: e.recursive_object,
        locations: e.locations || "[]",
        active: !1
      };
      A(!1), await q({
        code: "update_immunization",
        parameters: { ...t }
      }), M(), p({
        message: "Immunization status changed Successfully!",
        type: "success"
      });
    } catch (t) {
      console.error(t), p({ type: "error", message: "error toggling status" });
    }
  };
  return /* @__PURE__ */ w(k, { container: !0, justifyContent: "flex-end", className: "mt-5 mr-5", children: [
    _ && /* @__PURE__ */ i(
      Q,
      {
        configuredQuery: s,
        open: _,
        onClose: () => {
          T((e) => !e);
        },
        dataTestId: "eventconfiguration-query-showflywayquery"
      }
    ),
    /* @__PURE__ */ w(le, { isLoading: l, children: [
      /* @__PURE__ */ w(k, { item: !0, children: [
        /* @__PURE__ */ i(
          B,
          {
            className: "bg-white p-0 m-0",
            placeholder: "Search code",
            sx: {
              "& .MuiInputBase-root": { height: "35px" },
              // Controls the overall input height
              "& .MuiInputBase-input": { padding: "6px 12px" }
              // Adjust text padding inside input
            },
            value: m,
            onChange: K
          }
        ),
        (j == null ? void 0 : j.canGenerateFlyway) && /* @__PURE__ */ i(
          x,
          {
            className: "mb-4 ml-4",
            variant: "contained",
            onClick: () => {
              $((e) => !e);
            },
            size: "small",
            "data-testid": "immunizationList-button-add",
            children: z(v ? "Hide Selection" : "Select Immunization")
          }
        ),
        v && !_ && /* @__PURE__ */ i(
          x,
          {
            className: "mb-4 ml-4",
            variant: "contained",
            onClick: () => {
              X();
            },
            size: "small",
            "data-testid": "immunizationList-button-add",
            children: z("Show Flyway")
          }
        )
      ] }),
      /* @__PURE__ */ i(k, { size: { xs: 12 }, children: /* @__PURE__ */ i(
        ce,
        {
          dataTestId: "Immunization-configurator-customizedtable",
          columns: H,
          tableData: b,
          paginationConfig: {
            pagination: !0,
            rowsPerPageInTable: 20
          },
          actions: W,
          rowSelectionConfig: {
            rowSelectionEnabled: v,
            selectedRows: I,
            setSelectedRows: a
          },
          styleConfig: { tableStyle: { maxHeight: 45 } },
          isLoading: l,
          strip: !0
        }
      ) })
    ] }),
    /* @__PURE__ */ i(
      P,
      {
        open: r,
        description: "Are you sure you want to change the state of this Immunization ?",
        title: "CONFIRM ACTION",
        handleClick: () => Y(y),
        handleClose: () => A(!1)
      }
    )
  ] });
};
export {
  Le as default
};
//# sourceMappingURL=ImmunizationConfigurationsList-CQnxWa09-Bbr0iyGy.js.map
