import { jsx as e, jsxs as l } from "react/jsx-runtime";
import { Drawer as he, Typography as m, Button as x, Table as L, TableHead as z, TableRow as N, TableCell as c, TableBody as j, Divider as be } from "@mui/material";
import { Grid as h, Box as ye, Stack as ge } from "@mui/system";
import S from "prop-types";
import Q from "@/views/custom-components/CustomTextField";
import { useForm as we } from "react-hook-form";
import * as X from "yup";
import { yupResolver as ve } from "@hookform/resolvers/yup";
import Ne, { useRef as Y, useState as E, useEffect as B } from "react";
import Z from "@/views/custom-components/CustomConfirmationModal";
import { showToast as W } from "@/common/toaster/toaster";
import Ce from "@/views/custom-components/CustomCheckBox";
import { api as Ae } from "@/common/interceptors/AxiosInterceptor";
import Te from "@/hooks/useTrackEvent";
import D from "@/views/custom-components/CustomAutoComplete";
import { useTranslateProvider as Re } from "@/common/languageTranslator/TranslationContext";
import { faTrash as ee } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon as re } from "@fortawesome/react-fontawesome";
const Pe = (R) => Ae.post("/notificationtype", R);
function Ie({ open: R, handleClose: _, data: f, roleData: y }) {
  var G, H;
  const P = Y(null), F = Y(!1), [O, $] = E([]), [g, U] = E(null), [q, v] = E(0), [oe, te] = E(null), { translate: n } = Re(), ae = X.object().shape({
    name: X.string().required("Enter Name")
  });
  B(() => {
    if (P.current) {
      let o = P.current;
      return () => {
        M("conversion_event", {
          form: o,
          form_name: "Add Widget Role",
          submit: F.current
        });
      };
    }
  }, [P.current]);
  const {
    control: C,
    formState: { errors: I },
    handleSubmit: le,
    setValue: p,
    getValues: w,
    watch: de,
    reset: se
  } = we({
    defaultValues: { selectedPerformer: [] },
    mode: "onChange",
    resolver: ve(ae)
  }), i = de();
  B(() => {
    var o;
    p("name", f.notificationName), (o = f == null ? void 0 : f.roles) != null && o.length && p(
      "roles",
      f.roles ? f.roles.map((r) => y == null ? void 0 : y.find((t) => t.name === r)).filter((r) => r !== void 0) : []
    ), f.escalationLevels || (f.escalationLevels = []), p("escalationLevels", f.escalationLevels);
  }, [R]);
  const ne = (o, r) => {
    const t = o == null ? void 0 : o.map((a) => a.id);
    p(`selectedPerformer[${r}].roles`, t);
  }, ce = (o, r, t) => {
    const a = w("escalationLevels");
    a[r].performAction[t] = o, p("escalationLevels", a);
  }, ie = () => {
    const o = i.roles || [], r = [...o];
    O.forEach((t) => {
      o.some((d) => d.id === t.id) || r.push(t);
    }), p("roles", r), $([]);
  };
  B(() => {
    const o = w("selectedPerformer"), r = (i == null ? void 0 : i.roles) || [], t = o.map((a) => {
      const d = ((a == null ? void 0 : a.roles) || []).filter(
        (u) => r.some((A) => A.id === u)
      );
      return { ...a, roles: d };
    });
    p("selectedPerformer", t, { shouldValidate: !0 });
  }, [i.roles]);
  const me = (o, r) => {
    const t = w("escalationLevels"), a = w("selectedPerformer");
    t[r].roles = [
      .../* @__PURE__ */ new Set([
        ...t[r].roles,
        ...a[r].roles
      ])
    ], a[r].roles.forEach((d) => {
      t[r].performAction[d] = t[r].performAction[d] || !1;
    }), a[r].roles = [], p("escalationLevels", t), p("selectedPerformer", a);
  }, pe = () => {
    try {
      const r = w("roles").filter((d) => d.id !== g);
      p("roles", [...r]);
      const a = w("escalationLevels").map(
        (d) => {
          const u = d.roles.filter(
            (V) => V !== g
          ), { [g]: A, ...k } = d.performAction;
          return {
            ...d,
            roles: u,
            performAction: k
          };
        }
      );
      p("escalationLevels", a), v(0);
    } catch (o) {
      W({ message: o, type: "error" });
    }
  }, ue = (o, r) => {
    try {
      const t = w("escalationLevels");
      t[r].roles = t[r].roles.filter(
        (u) => u !== g
      );
      const { [g]: a, ...d } = t[r].performAction;
      t[r].performAction = d, p("escalationValues", [...t]), v(0);
    } catch (t) {
      W({ message: t, type: "error" });
    }
  }, M = Te(), fe = async (o) => {
    try {
      M("button_click", {
        button_name: f ? "update widget  button" : "add widget  button",
        button_type: "submit",
        button_id: "addroledrawer-button-submit"
      });
      const { roles: r = [], escalationLevels: t } = o, a = r.map((u) => u.id), d = { ...f, escalationLevels: t, roles: a };
      await Pe(d).catch((u) => {
        console.error("error in updating notification", u);
      }), W({ message: "Widget Updated Successfully", type: "success" }), F.current = !0, _(!0);
    } catch (r) {
      console.error(r);
    }
  };
  return /* @__PURE__ */ e(
    he,
    {
      open: R,
      anchor: "right",
      onClose: _,
      className: "z-[1300]",
      "data-testid": "addroledrawer-drawer-container",
      children: /* @__PURE__ */ l(
        h,
        {
          container: !0,
          className: "flex flex-col w-full md:w-[600px] ",
          ref: P,
          children: [
            /* @__PURE__ */ e(
              h,
              {
                p: 1,
                alignContent: "flex-start",
                className: "p-2.5 px-5 flex border-b font-medium text-lg",
                "data-testid": "addroledrawer-grid-header uppercase",
                children: n("Assign Role")
              }
            ),
            /* @__PURE__ */ l(
              h,
              {
                container: !0,
                display: "flex",
                flexDirection: "column",
                p: 1,
                "data-testid": "addroledrawer-grid-content",
                children: [
                  /* @__PURE__ */ l(h, { "data-testid": "addroledrawer-grid-name", children: [
                    /* @__PURE__ */ l(m, { variant: "body2", children: [
                      n("Name"),
                      /* @__PURE__ */ e("span", { className: "text-red-500 ml-1", children: "*" })
                    ] }),
                    /* @__PURE__ */ e(
                      Q,
                      {
                        id: "name",
                        control: C,
                        name: "name",
                        errors: I,
                        InputProps: {
                          readOnly: !0
                        },
                        dataTestId: "addroledrawer-textfield-name"
                      }
                    )
                  ] }),
                  /* @__PURE__ */ l(h, { "data-testid": "addroledrawer-grid-actionby", children: [
                    /* @__PURE__ */ e(m, { variant: "body2", mt: 1, children: n("Select Role") }),
                    /* @__PURE__ */ l(h, { container: !0, display: "flex", flexDirection: "row", children: [
                      /* @__PURE__ */ e(h, { width: "70%", mr: 2, children: /* @__PURE__ */ e(
                        D,
                        {
                          name: "role",
                          control: C,
                          value: O,
                          options: y,
                          getOptionLabel: (o) => o.name,
                          errors: I,
                          dataTestId: "addroledrawer-select-roles",
                          onChange: (o, r) => $(r)
                        }
                      ) }),
                      /* @__PURE__ */ e(h, { className: "pt-2", children: /* @__PURE__ */ e(
                        x,
                        {
                          variant: "contained",
                          size: "small",
                          disabled: !O.length,
                          onClick: ie,
                          "data-testid": "addroledrawer-button-add",
                          children: n("Assign")
                        }
                      ) })
                    ] })
                  ] }),
                  /* @__PURE__ */ e(h, { "data-testid": "addroledrawer-grid-table", children: /* @__PURE__ */ l(
                    L,
                    {
                      "data-testid": "addroledrawer-table",
                      className: "border border-gray-300",
                      children: [
                        /* @__PURE__ */ e(z, { children: /* @__PURE__ */ l(N, { children: [
                          /* @__PURE__ */ e(c, { className: "border-r border-gray-300 p-2", children: /* @__PURE__ */ e(m, { variant: "body2", className: "font-bold", children: `${n("Role")}${n("name")} (${n("Assigned to")})` }) }),
                          /* @__PURE__ */ e(c, { className: "p-2", children: /* @__PURE__ */ e(m, { variant: "body2", className: "font-bold", children: n("Delete") }) })
                        ] }) }),
                        /* @__PURE__ */ e(j, { children: (G = i == null ? void 0 : i.roles) == null ? void 0 : G.map((o, r) => /* @__PURE__ */ l(
                          N,
                          {
                            "data-testid": "addroledrawer-tablerow-roles",
                            children: [
                              /* @__PURE__ */ e(c, { className: "border border-gray-300 p-2", children: /* @__PURE__ */ e(m, { variant: "caption", children: o.name }) }),
                              /* @__PURE__ */ l(c, { className: "p-2", children: [
                                /* @__PURE__ */ e(
                                  re,
                                  {
                                    icon: ee,
                                    className: "text-[18px] text-[var(--color-error)]",
                                    onClick: () => {
                                      v(1), U(o.id);
                                    },
                                    "data-testid": "addroledrawer-icon-delete"
                                  }
                                ),
                                /* @__PURE__ */ e(
                                  Z,
                                  {
                                    open: q === 1 && g === o.id,
                                    handleClose: () => v(0),
                                    handleClick: (t) => pe(),
                                    title: "CONFIRM ACTION",
                                    description: "Are you sure you want to delete this role? It will also delete role from each escalation level.",
                                    dataTestId: "addroledrawer-modal-confirmdelete"
                                  }
                                )
                              ] })
                            ]
                          },
                          o.id
                        )) })
                      ]
                    }
                  ) }),
                  (H = i.escalationLevels) == null ? void 0 : H.map((o, r) => {
                    var t, a, d, u, A, k, V, J;
                    return /* @__PURE__ */ l(Ne.Fragment, { children: [
                      /* @__PURE__ */ e(h, { "data-testid": "addroledrawer-grid-escalationlevel", children: /* @__PURE__ */ l(L, { className: "border border-gray-300", children: [
                        /* @__PURE__ */ e(z, { children: /* @__PURE__ */ l(N, { children: [
                          /* @__PURE__ */ e(c, { className: "border-r border-gray-300 p-2 w-80", children: /* @__PURE__ */ e(m, { variant: "body2", className: "font-bold", children: n("Escalation Level") }) }),
                          /* @__PURE__ */ e(c, { className: "border-r border-gray-300 p-2 w-60", children: /* @__PURE__ */ e(m, { variant: "body2", className: "font-bold", children: n("Performer") }) }),
                          /* @__PURE__ */ e(c, { className: "p-2 w-40 ", children: /* @__PURE__ */ e(m, { variant: "body2", className: "font-bold", children: n("Action") }) })
                        ] }) }),
                        /* @__PURE__ */ e(j, { children: /* @__PURE__ */ l(N, { "data-testid": "addroledrawer-tablerow-escalationperformer", children: [
                          /* @__PURE__ */ e(c, { className: "border-r border-gray-300 p-2", children: /* @__PURE__ */ e(
                            Q,
                            {
                              id: "escalationLevel",
                              control: C,
                              name: `escalationLevelData[${r}].name`,
                              defaultValue: o == null ? void 0 : o.name,
                              errors: I,
                              disabled: !0,
                              dataTestId: "addroledrawer-textfield-escalationlevel"
                            }
                          ) }),
                          /* @__PURE__ */ e(c, { className: "border-r border-gray-300 p-2", children: /* @__PURE__ */ e(
                            D,
                            {
                              control: C,
                              value: (a = (t = i.selectedPerformer) == null ? void 0 : t[r]) != null && a.roles ? (u = (d = i.selectedPerformer[r]) == null ? void 0 : d.roles) == null ? void 0 : u.map(
                                (s) => y.find((b) => b.id === s)
                              ) : [],
                              name: `selectedPerformer[${r}].roles`,
                              options: (A = i == null ? void 0 : i.roles) == null ? void 0 : A.map(
                                (s) => y.find((b) => b.id === s.id)
                              ),
                              getOptionLabel: (s) => s == null ? void 0 : s.name,
                              onChange: (s, b) => ne(b, r),
                              dataTestId: "addroledrawer-select-performer",
                              errors: I
                            }
                          ) }),
                          /* @__PURE__ */ e(c, { children: /* @__PURE__ */ e(
                            x,
                            {
                              variant: "contained",
                              size: "small",
                              disabled: !((V = (k = i.selectedPerformer[r]) == null ? void 0 : k.roles) != null && V.length),
                              onClick: (s) => me(s, r),
                              "data-testid": "addroledrawer-button-addperformer",
                              children: n("Add")
                            }
                          ) })
                        ] }) })
                      ] }) }),
                      /* @__PURE__ */ e(h, { children: o.roles.length ? /* @__PURE__ */ l(
                        L,
                        {
                          className: "border border-gray-300",
                          "data-testid": "addroledrawer-table-performactionroles",
                          children: [
                            /* @__PURE__ */ e(z, { children: /* @__PURE__ */ l(N, { children: [
                              /* @__PURE__ */ e(c, { className: "border border-gray-300 p-2", children: /* @__PURE__ */ e(m, { variant: "body2", className: "font-bold", children: n("Name") }) }),
                              /* @__PURE__ */ e(c, { className: "border border-gray-300 p-2", children: /* @__PURE__ */ e(m, { variant: "body2", className: "font-bold", children: n("Roles with perform action") }) }),
                              /* @__PURE__ */ e(c, { className: "p-2", children: /* @__PURE__ */ e(m, { variant: "body2", className: "font-bold", children: n("Delete") }) })
                            ] }) }),
                            /* @__PURE__ */ e(j, { children: (J = o.roles) == null ? void 0 : J.filter(
                              (s) => y.find((b) => b.id === s)
                            ).map((s, b) => {
                              var K;
                              return /* @__PURE__ */ l(
                                N,
                                {
                                  "data-testid": "addroledrawer-tablerow-roleactions",
                                  children: [
                                    b === 0 && /* @__PURE__ */ e(
                                      c,
                                      {
                                        className: "border border-gray-300 p-2",
                                        rowSpan: o.roles.length,
                                        children: o.name
                                      }
                                    ),
                                    /* @__PURE__ */ e(c, { className: "border border-gray-300 p-2", children: /* @__PURE__ */ l(ye, { className: "flex items-center", children: [
                                      /* @__PURE__ */ e(
                                        Ce,
                                        {
                                          name: `${r}-${b}`,
                                          control: C,
                                          isFullWidth: !1,
                                          checked: o.performAction[s],
                                          onChange: (T) => ce(T, r, s),
                                          "data-testid": "addroledrawer-checkbox-performaction"
                                        }
                                      ),
                                      /* @__PURE__ */ e(m, { variant: "caption", children: (K = y.find((T) => T.id === s)) == null ? void 0 : K.name })
                                    ] }) }),
                                    /* @__PURE__ */ l(c, { className: "border border-gray-300 p-2", children: [
                                      /* @__PURE__ */ e(
                                        re,
                                        {
                                          icon: ee,
                                          className: "text-[18px] text-[var(--color-error)]",
                                          onClick: () => {
                                            v(2), U(s), te(r);
                                          },
                                          "data-testid": "addroledrawer-icon-deleterole"
                                        }
                                      ),
                                      /* @__PURE__ */ e(
                                        Z,
                                        {
                                          open: q === 2 && g === s && oe === r,
                                          handleClose: () => v(0),
                                          handleClick: (T) => {
                                            ue(T, r);
                                          },
                                          title: "CONFIRM ACTION",
                                          description: "Are you sure you want to delete this role?",
                                          dataTestId: "addroledrawer-modal-confirmdeleterole"
                                        }
                                      )
                                    ] })
                                  ]
                                },
                                s
                              );
                            }) })
                          ]
                        }
                      ) : null })
                    ] }, o.id);
                  })
                ]
              }
            ),
            /* @__PURE__ */ e(be, { "data-testid": "addroledrawer-divider" }),
            /* @__PURE__ */ l(
              ge,
              {
                direction: "row",
                spacing: 2,
                justifyContent: "flex-end",
                mt: 2,
                mb: 1.5,
                children: [
                  /* @__PURE__ */ e(
                    x,
                    {
                      variant: "contained",
                      color: "secondary",
                      size: "small",
                      onClick: () => {
                        M("button_click", {
                          button_name: "cancel widget button",
                          button_type: "cancel",
                          button_id: "addroledrawer-button-close"
                        }), se(), $([]), _();
                      },
                      "data-testid": "addroledrawer-button-close",
                      children: /* @__PURE__ */ e(m, { variant: "caption", children: `${n("Close")}` })
                    }
                  ),
                  /* @__PURE__ */ e(
                    x,
                    {
                      variant: "contained",
                      color: "primary",
                      className: "mr-2",
                      size: "small",
                      onClick: le(fe),
                      "data-testid": "addroledrawer-button-submit",
                      children: n("Update")
                    }
                  )
                ]
              }
            )
          ]
        }
      )
    }
  );
}
Ie.propTypes = {
  open: S.any,
  handleClose: S.func,
  data: S.any,
  roleData: S.any
};
export {
  Ie as default
};
//# sourceMappingURL=AddRoleDrawer-ZK1eejxI.js.map
