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