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