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