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