import { jsx as r, jsxs as m, Fragment as Z } from "react/jsx-runtime";
import { useRef as oe, useState as z, useCallback as je, useMemo as qe, useEffect as ie } from "react";
import f from "prop-types";
import { useForm as ze } from "react-hook-form";
import { yupResolver as Ie } from "@hookform/resolvers/yup";
import b from "@mui/material/Grid2";
import * as x from "yup";
import { Modal as Oe, Typography as Re, IconButton as Be, FormControl as I, Box as w, Button as ue } from "@mui/material";
import U from "@/views/custom-components/CustomTextField";
import { showToast as E } from "@/common/toaster/toaster";
import { t as Me, e as Pe, f as F, h as Ke, i as Ge } from "./ManageTranslation-BTxvSYKb.js";
import { executeQuery as me, execute as W } from "@/common/services/GlobalApis";
import Le from "@/views/custom-components/CustomAutoComplete";
import Qe from "@/hooks/useTrackEvent";
import { useTranslateProvider as Ue } from "@/common/languageTranslator/TranslationContext";
import We from "@mui/material/Tabs";
import Xe from "@mui/material/Tab";
import { faXmark as He } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon as Je } from "@fortawesome/react-fontawesome";
import Ye from "@/views/custom-components/CustomDropdown";
function de(V) {
  const { children: X, value: M, index: N, selectedTab: y, ...u } = V;
  return /* @__PURE__ */ r(
    "div",
    {
      role: "tabpanel",
      hidden: M !== y,
      id: `simple-tabpanel-${N}`,
      "aria-labelledby": `simple-tab-${N}`,
      ...u,
      children: M === y && /* @__PURE__ */ r(w, { className: "p-3", children: X })
    }
  );
}
de.propTypes = {
  selectedTab: f.any,
  children: f.node,
  index: f.number.isRequired,
  value: f.number.isRequired
};
function Ze(V) {
  return {
    id: `simple-tab-${V}`,
    "aria-controls": `simple-tabpanel-${V}`
  };
}
const Fe = ({
  open: V,
  handleClose: X,
  apps: M,
  languageList: N = [],
  addAppFlag: y = !1,
  fieldsData: u,
  refetch: P,
  addNameSpaceFlag: S = !1,
  editLabelFlag: _ = !1,
  labelKey: D = null,
  isLoading: he = !1
}) => {
  var ae;
  const K = (ae = N == null ? void 0 : N.find(
    (e) => e.languageValue === "English"
  )) == null ? void 0 : ae.id, ee = oe(null), O = oe(!1), H = Qe(), [A, te] = z([]), [g, se] = z([]), [pe, fe] = z([]), [R, be] = z([]), [J, re] = z(null), [ye, ve] = z([]), { translate: C } = Ue(), xe = (e, s) => {
    re(s);
  };
  let B;
  if (y) {
    const e = u == null ? void 0 : u.reduce((s, t) => (s[`${t.languagevalue}`] = x.string().required(
      `Enter value for ${t.languagevalue}`
    ), s), {});
    B = x.object().shape({
      apps: x.array().min(1, "Select at least one App").required("Select App"),
      ...e
      // Spread the dynamically created validations
    });
  } else if (S)
    B = x.object().shape({
      namespace: x.array().min(1, "Select at least one Namespace").required("Select Namespace")
    });
  else if (_) {
    let e = R.reduce((s, t) => ((t == null ? void 0 : t.languagevalue) !== "English" && (t == null ? void 0 : t.appvalue) === J && (s[`${t.app}_${t.languagevalue}`] = x.string().required(`Enter value for ${t.languagevalue}`).test(
      "placeholders-match",
      "Placeholders do not match the original English text.",
      function(l) {
        const { path: n, createError: a, parent: p } = this, o = (p == null ? void 0 : p[`${t.app}_English`]) || "", c = L(o), d = L(l);
        return Object.keys(c).length === Object.keys(d).length && Object.keys(c).every(
          (k) => d[k] === c[k]
        ) || a({
          path: n,
          message: "Placeholders do not match the original English text."
        });
      }
    )), s), {});
    B = x.object().shape({
      ...e
    });
  } else {
    const e = N.reduce((s, t) => ((t == null ? void 0 : t.language_value) !== "English" && (s[t.language_value] = x.string().required(`Enter value for ${t.language_value}`).test(
      "placeholders-match",
      "Placeholders do not match the original English text.",
      function(l) {
        const { path: n, createError: a, parent: p } = this, o = (p == null ? void 0 : p.englishValue) || "", c = L(o), d = L(l);
        return Object.keys(c).length === Object.keys(d).length && Object.keys(c).every(
          (k) => d[k] === c[k]
        ) || a({
          path: n,
          message: "Placeholders do not match the original English text."
        });
      }
    )), s), {});
    B = x.object().shape({
      apps: x.array().min(1, "Select at least one App").required("Select App"),
      namespace: x.array().min(1, "Select at least one Namespace").required("Select Namespace"),
      englishValue: x.string().required("Enter Value for English"),
      ...e
      // Spread the dynamically created validations
    });
  }
  const le = je(async (e) => {
    try {
      await Ve(e);
    } catch (s) {
      console.error(s);
    }
  }, []), Ne = (e, s) => {
    let t;
    return (...l) => {
      t && clearTimeout(t), t = setTimeout(() => {
        e(...l);
      }, s);
    };
  }, ge = qe(
    () => Ne(le, 300),
    [le]
  ), {
    control: $,
    handleSubmit: _e,
    reset: ke,
    setValue: G,
    getValues: ne,
    formState: { errors: j }
  } = ze({
    defaultValues: {},
    resolver: Ie(B),
    mode: "onChange"
  }), L = (e) => {
    if (!e) return {};
    const s = [...e.matchAll(/{(.*?)}/g)], t = {};
    return s.forEach((l) => {
      const n = l[1];
      t[n] = (t[n] || 0) + 1;
    }), t;
  };
  ie(() => {
    if (Ce(), u && y) {
      let e = [];
      u == null || u.forEach((s) => {
        G(s == null ? void 0 : s.languagevalue, s == null ? void 0 : s.value), e.push({ id: s == null ? void 0 : s.language, value: s == null ? void 0 : s.value });
      }), se(e), Se();
    }
    u && S && we(u.key);
  }, [u]), ie(() => {
    _ && Ee();
  }, [_]);
  const Ee = async () => {
    var e, s, t, l;
    try {
      const a = await me({
        code: "labels_selected_apps_for_editing",
        parameters: { key: D }
      });
      be((e = a == null ? void 0 : a.data) == null ? void 0 : e.result);
      let p = (t = (s = a == null ? void 0 : a.data) == null ? void 0 : s.result) == null ? void 0 : t.map((o) => o.appvalue).filter((o, c, d) => c === d.findIndex((v) => v === o));
      (l = a == null ? void 0 : a.data) == null || l.result.forEach((o) => {
        const c = `${o.app}_${o.languagevalue}`;
        G(c, o.value || "");
      }), te(p), re(p[0]);
    } catch (n) {
      console.error(n), E({ message: "Error in editing label", type: "error" });
    }
  }, Y = (e, s, t = null) => {
    let l = [...g], n = !1;
    l == null || l.forEach((a) => {
      (a == null ? void 0 : a.id) === e && (a.value = s, n = !0);
    }), n || (t ? l.push({ id: e, value: s, labelid: t }) : l.push({ id: e, value: s })), se(l);
  }, we = async (e) => {
    var s, t;
    try {
      const l = await W({
        code: "get_namespaces_from_key",
        parameters: { key: e }
      });
      let n = (t = (s = l == null ? void 0 : l.data) == null ? void 0 : s.result) == null ? void 0 : t.map((a) => a.value);
      G("namespace", n || []);
    } catch (l) {
      console.error(l);
    }
  }, Ce = async () => {
    var e;
    try {
      const s = await W({
        code: "get_distinct_namespce",
        parameters: {}
      });
      ve((e = s == null ? void 0 : s.data) == null ? void 0 : e.result);
    } catch (s) {
      console.error(s);
    }
  }, Se = async () => {
    var e, s, t;
    try {
      let n = {
        code: "labels_selected_apps_for_editing",
        parameters: { key: (e = u[0]) == null ? void 0 : e.key.replace(/'/g, "''") }
      };
      const a = await me(n);
      let p = (t = (s = a == null ? void 0 : a.data) == null ? void 0 : s.result) == null ? void 0 : t.map((o) => o.appvalue).filter((o, c, d) => c === d.findIndex((v) => v === o)).join(", ");
      te(p);
    } catch (l) {
      console.error(l), E({ message: "Error in Adding App", type: "error" });
    }
  }, Ae = (e, s) => {
    fe(s), G("apps", s);
  }, Te = (e) => (e == null ? void 0 : e.appValue) || "", T = () => {
    H("conversion_event", {
      form: ee.current,
      form_name: "Add Label Configuration",
      submit: O.current
    }), X();
  }, Ve = async (e) => {
    var s;
    try {
      let t;
      if ((e == null ? void 0 : e.id) === K) {
        let l;
        y ? (t = g.filter((n) => n.id !== K).map((n) => n.id).join(","), g == null || g.forEach((n) => {
          (n == null ? void 0 : n.id) === K && (l = n == null ? void 0 : n.value);
        })) : (t = N.filter((n) => n.languageKey !== "en").map((n) => n.id).join(","), l = (s = ne()) == null ? void 0 : s.englishValue), l ? await Me(t, l) : E({ message: "Enter english text", type: "info" });
      }
    } catch (t) {
      console.error(t), E({ message: "Error in Translation", type: "error" });
    }
  }, $e = async (e) => {
    var s, t, l, n, a, p;
    try {
      H("button_click", {
        button_name: "add-label-add-button",
        button_type: "submit",
        button_id: "add-label-submit-button"
      });
      let o = [];
      if (y)
        (s = e == null ? void 0 : e.apps) == null || s.forEach((c) => {
          g == null || g.forEach((d) => {
            o.push({
              language: d == null ? void 0 : d.id,
              value: d == null ? void 0 : d.value,
              app: c == null ? void 0 : c.id,
              isActive: !0,
              key: u[0].key
            });
          });
        }), await F(o), O.current = !0, P(), E({ message: "App Added Successfully", type: "success" }), T();
      else if (S) {
        let c = (e == null ? void 0 : e.namespace) || [];
        await Ke({
          key: u.key,
          namespace: c
        }), O.current = !0, P(), E({
          message: "NameSpace Updated Successfully",
          type: "success"
        }), T();
      } else if (_) {
        const c = ne(), d = Object.entries(c).reduce(
          (v, [k, i]) => {
            const [h, q] = k.split("_");
            if (i === "") return v;
            const Q = R.find(
              (ce) => ce.app === parseInt(h) && ce.languagevalue === q
            );
            return Q && Q.value !== i && v.push({
              id: Q.id || null,
              language: Q.language || q,
              value: i,
              app: parseInt(h),
              isActive: !0,
              key: D
            }), v;
          },
          []
        );
        await F(d), O.current = !0, P(), E({ message: "Label Updated Successfully", type: "success" }), T();
      } else {
        const c = e.englishValue.replace(/ /g, "");
        (t = e == null ? void 0 : e.apps) == null || t.forEach((i) => {
          o.push({
            language: K,
            value: e == null ? void 0 : e.englishValue,
            app: i == null ? void 0 : i.id,
            isActive: !0,
            key: c
          }), g == null || g.forEach((h) => {
            o.push({
              language: h == null ? void 0 : h.id,
              value: h == null ? void 0 : h.value,
              app: i == null ? void 0 : i.id,
              isActive: !0,
              key: c
            });
          });
        });
        let d = (e == null ? void 0 : e.namespace) || [], v = [];
        for (const i of d)
          try {
            const h = await W({
              code: "check_key_namespace_exist",
              parameters: {
                key: c,
                namespace: i
              }
            });
            ((n = (l = h == null ? void 0 : h.data) == null ? void 0 : l.result) == null ? void 0 : n.length) === 0 && v.push(i);
          } catch (h) {
            console.error("Error while checking namespace:", i, h);
          }
        await Ge({
          key: c,
          namespace: v
        });
        let k = !1;
        for (const i of o) {
          let h = {
            code: "translation_label_app_language_key_check",
            parameters: {
              key: i == null ? void 0 : i.key,
              language: i == null ? void 0 : i.language,
              app: i == null ? void 0 : i.app
            }
          };
          const q = await W(h);
          if (((p = (a = q == null ? void 0 : q.data) == null ? void 0 : a.result) == null ? void 0 : p.length) > 0) {
            E({
              message: "The Label containing Same App, Language and Key Already Exists.",
              type: "error"
            }), k = !0;
            break;
          }
        }
        !k && o.length > 0 && (await F(o), O.current = !0, P(), E({
          message: "Label Added Successfully",
          type: "success"
        }), T());
      }
    } catch (o) {
      console.error(o), E({ message: "Error in Adding Label", type: "error" });
    }
  };
  return /* @__PURE__ */ r(
    Oe,
    {
      "data-testid": "add-label-modal",
      open: V,
      onClose: () => {
        T(), ke();
      },
      className: "translation-modal",
      children: /* @__PURE__ */ r(Pe, { isLoading: he, children: /* @__PURE__ */ m(
        b,
        {
          container: !0,
          sx: {
            display: "flex",
            flexDirection: "column",
            position: "absolute",
            top: 40,
            left: "50%",
            transform: "translateX(-50%)",
            width: "95%",
            maxWidth: { sm: 600, md: 700, lg: 800 },
            bgcolor: "background.paper",
            boxShadow: 24,
            border: 1,
            borderColor: "divider",
            borderRadius: 0.5
          },
          children: [
            /* @__PURE__ */ m(
              b,
              {
                sx: {
                  p: 1.25,
                  px: 3,
                  display: "flex",
                  justifyContent: "space-between",
                  borderBottom: 1,
                  borderColor: "divider"
                },
                "data-testid": "add-label-header",
                children: [
                  /* @__PURE__ */ m(
                    Re,
                    {
                      variant: "body1",
                      className: "text-customBlue",
                      sx: { fontWeight: "medium", fontSize: "1.125rem" },
                      children: [
                        !y && !S && !_ && C("Add Label"),
                        S && C("Add NameSpace"),
                        y && C("Add App"),
                        _ && C("Edit Label")
                      ]
                    }
                  ),
                  /* @__PURE__ */ r(
                    Be,
                    {
                      size: "small",
                      onClick: () => {
                        T();
                      },
                      "data-testid": "add-label-close-button",
                      children: /* @__PURE__ */ r(Je, { icon: He })
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ r(b, { item: "true", className: "overflow-y-auto max-h-[60vh]", children: /* @__PURE__ */ m(
              b,
              {
                container: !0,
                justifyContent: "flex-start",
                className: "p-3 pl-5 pr-7",
                children: [
                  S && /* @__PURE__ */ m("div", { children: [
                    "Add Namespace for ",
                    u == null ? void 0 : u.key
                  ] }),
                  y && /* @__PURE__ */ m("div", { children: [
                    "Label already exists in ",
                    A
                  ] }),
                  /* @__PURE__ */ m(
                    "form",
                    {
                      onSubmit: _e($e),
                      className: "w-full",
                      ref: ee,
                      children: [
                        !S && !_ && /* @__PURE__ */ r(b, { item: "true", className: "pb-[5px]", children: /* @__PURE__ */ r(
                          I,
                          {
                            variant: "outlined",
                            className: "w-full",
                            "data-testid": "add-label-base-date-field",
                            children: /* @__PURE__ */ m(w, { className: "custom-flex-container", children: [
                              /* @__PURE__ */ m("div", { className: "w-[30%]", children: [
                                C("App"),
                                /* @__PURE__ */ r("span", { className: "text-red-500 ml-1", children: "*" })
                              ] }),
                              /* @__PURE__ */ r(
                                Le,
                                {
                                  control: $,
                                  name: "apps",
                                  size: "small",
                                  options: M || [],
                                  errors: j,
                                  value: pe,
                                  onChange: Ae,
                                  getOptionLabel: Te
                                }
                              )
                            ] })
                          }
                        ) }),
                        !y && !_ && /* @__PURE__ */ r(b, { item: "true", className: "pb-[5px]", children: /* @__PURE__ */ r(
                          I,
                          {
                            variant: "outlined",
                            className: "w-full",
                            "data-testid": "add-label-base-date-field",
                            children: /* @__PURE__ */ m(w, { className: "custom-flex-container", children: [
                              /* @__PURE__ */ m("div", { className: "w-[30%]", children: [
                                C("Namespace"),
                                /* @__PURE__ */ r("span", { className: "text-red-500 ml-1", children: "*" }),
                                /* @__PURE__ */ r("br", {}),
                                /* @__PURE__ */ r("div", { className: "text-sm text-gray-600 pr-3", children: "(Note: Add to General if no specific namespace)" })
                              ] }),
                              /* @__PURE__ */ r(
                                Ye,
                                {
                                  control: $,
                                  name: "namespace",
                                  options: ye || [],
                                  errors: j,
                                  displayName: "label",
                                  optionValue: "value",
                                  multiple: !0
                                }
                              )
                            ] })
                          }
                        ) }),
                        !y && !S && !_ && /* @__PURE__ */ m(Z, { children: [
                          /* @__PURE__ */ r(b, { item: "true", className: "pb-[5px]", children: /* @__PURE__ */ r(
                            I,
                            {
                              variant: "outlined",
                              className: "w-full",
                              "data-testid": "add-label-field",
                              children: /* @__PURE__ */ m(
                                w,
                                {
                                  className: "custom-flex-container",
                                  display: "flex",
                                  children: [
                                    /* @__PURE__ */ m("div", { className: "w-[30%]", children: [
                                      C("English"),
                                      /* @__PURE__ */ r("span", { className: "text-red-500 ml-1", children: "*" })
                                    ] }),
                                    /* @__PURE__ */ r(
                                      U,
                                      {
                                        control: $,
                                        id: "englishValue",
                                        name: "englishValue",
                                        errors: j,
                                        label: "",
                                        size: "small",
                                        className: "w-full",
                                        "data-testid": "add-label-language-english"
                                      }
                                    )
                                  ]
                                }
                              )
                            }
                          ) }),
                          N == null ? void 0 : N.map((e, s) => {
                            if ((e == null ? void 0 : e.language_value) !== "English")
                              return /* @__PURE__ */ r(b, { item: "true", className: "pb-[5px]", children: /* @__PURE__ */ r(
                                I,
                                {
                                  variant: "outlined",
                                  className: "w-full",
                                  "data-testid": "add-label-base-date-field",
                                  children: /* @__PURE__ */ m(w, { className: "custom-flex-container", children: [
                                    /* @__PURE__ */ m("div", { className: "w-[30%]", children: [
                                      e == null ? void 0 : e.language_value,
                                      /* @__PURE__ */ r("span", { className: "text-red-500 ml-1", children: "*" })
                                    ] }),
                                    /* @__PURE__ */ r(
                                      U,
                                      {
                                        control: $,
                                        id: e == null ? void 0 : e.language_value,
                                        name: e == null ? void 0 : e.language_value,
                                        errors: j,
                                        onChange: (t) => {
                                          var l;
                                          Y(
                                            e == null ? void 0 : e.id,
                                            (l = t == null ? void 0 : t.target) == null ? void 0 : l.value
                                          );
                                        },
                                        label: "",
                                        size: "small",
                                        className: "w-full",
                                        "data-testid": "add-label-language"
                                      }
                                    )
                                  ] })
                                }
                              ) }, s + 1);
                          })
                        ] }),
                        y && /* @__PURE__ */ r(Z, { children: u == null ? void 0 : u.map((e, s) => /* @__PURE__ */ r(b, { item: "true", className: "pb-[5px]", children: /* @__PURE__ */ r(
                          I,
                          {
                            variant: "outlined",
                            className: "w-full",
                            "data-testid": "add-label-base-date-field",
                            children: /* @__PURE__ */ m(w, { className: "custom-flex-container", children: [
                              /* @__PURE__ */ m("div", { className: "w-[30%]", children: [
                                e == null ? void 0 : e.languagevalue,
                                /* @__PURE__ */ r("span", { className: "text-red-500 ml-1", children: "*" })
                              ] }),
                              /* @__PURE__ */ r(
                                U,
                                {
                                  control: $,
                                  id: e == null ? void 0 : e.languagevalue,
                                  name: e == null ? void 0 : e.languagevalue,
                                  errors: j,
                                  onChange: (t) => {
                                    var l;
                                    Y(
                                      e == null ? void 0 : e.language,
                                      (l = t == null ? void 0 : t.target) == null ? void 0 : l.value
                                    ), ge({ id: e == null ? void 0 : e.language });
                                  },
                                  label: "",
                                  size: "small",
                                  className: "w-full",
                                  "data-testid": "add-label-language"
                                }
                              )
                            ] })
                          }
                        ) }, s + 1)) }),
                        _ && /* @__PURE__ */ m(Z, { children: [
                          " ",
                          /* @__PURE__ */ r(b, { item: !0, className: "pb-[5px]", children: /* @__PURE__ */ r(w, { className: "w-full", children: /* @__PURE__ */ r(w, { className: "label-edit-tabs", children: /* @__PURE__ */ r(
                            We,
                            {
                              value: J,
                              onChange: xe,
                              "aria-label": "basic tabs example",
                              children: A == null ? void 0 : A.map((e, s) => /* @__PURE__ */ r(
                                Xe,
                                {
                                  label: e,
                                  value: e,
                                  ...Ze(s)
                                },
                                s + 1
                              ))
                            }
                          ) }) }) }),
                          A == null ? void 0 : A.map((e, s) => /* @__PURE__ */ r(b, { item: !0, children: /* @__PURE__ */ r(b, { children: /* @__PURE__ */ r(
                            de,
                            {
                              value: e,
                              selectedTab: J,
                              index: s,
                              children: R == null ? void 0 : R.map((t, l) => {
                                if ((t == null ? void 0 : t.appvalue) === e)
                                  return /* @__PURE__ */ r(b, { item: !0, className: "pb-[5px]", children: /* @__PURE__ */ r(
                                    I,
                                    {
                                      variant: "outlined",
                                      className: "w-full",
                                      "data-testid": "label-edit-field",
                                      children: /* @__PURE__ */ m(w, { className: "custom-flex-container", children: [
                                        /* @__PURE__ */ r("div", { className: "w-[30%]", children: t == null ? void 0 : t.languagevalue }),
                                        /* @__PURE__ */ r(
                                          U,
                                          {
                                            control: $,
                                            id: `${t == null ? void 0 : t.app}-${t.languagevalue}`,
                                            name: `${t == null ? void 0 : t.app}_${t.languagevalue}`,
                                            errors: j,
                                            onChange: (n) => {
                                              var a;
                                              return Y(
                                                t == null ? void 0 : t.language,
                                                (a = n == null ? void 0 : n.target) == null ? void 0 : a.value,
                                                t == null ? void 0 : t.id
                                              );
                                            },
                                            label: "",
                                            size: "small",
                                            className: "w-full",
                                            "data-testid": "label-edit-input"
                                          }
                                        )
                                      ] })
                                    }
                                  ) }, l + 1);
                              })
                            },
                            s + 1
                          ) }) }, s + 1))
                        ] }),
                        /* @__PURE__ */ r(b, { item: "true", className: "pb-[5px] flex justify-end", children: /* @__PURE__ */ m(w, { className: "custom-flex-button", children: [
                          /* @__PURE__ */ r(
                            ue,
                            {
                              size: "small",
                              variant: "contained",
                              "data-testid": "add-label-back-button",
                              color: "secondary",
                              onClick: () => {
                                T(), H("button_click", {
                                  button_name: "add-label-back-button",
                                  button_type: "cancel",
                                  button_id: "add-label-back-button"
                                });
                              },
                              children: C("Cancel")
                            }
                          ),
                          /* @__PURE__ */ r(
                            ue,
                            {
                              type: "submit",
                              size: "small",
                              variant: "contained",
                              "data-testid": "add-label-save-button",
                              color: "primary",
                              children: C("Save")
                            }
                          )
                        ] }) })
                      ]
                    }
                  )
                ]
              }
            ) })
          ]
        }
      ) })
    }
  );
};
Fe.propTypes = {
  open: f.any,
  handleClose: f.any,
  languageList: f.any,
  apps: f.any,
  addAppFlag: f.any,
  fieldsData: f.any,
  refetch: f.any,
  addNameSpaceFlag: f.any,
  editLabelFlag: f.any,
  labelKey: f.any,
  isLoading: f.any
};
export {
  Fe as default
};
//# sourceMappingURL=AddLabelModal-DE3ploGD.js.map
