'use strict';

var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var React = require('react');
var neetoAtoms = require('@bigbinary/neeto-atoms');
var classnames = require('classnames');
var lucideReact = require('lucide-react');
var initializers = require('@bigbinary/neeto-commons-frontend/v2/initializers');
var utils = require('@bigbinary/neeto-commons-frontend/v2/utils');
var hooks = require('@bigbinary/neeto-image-uploader-frontend/hooks');
var ramda = require('ramda');
var reactI18next = require('react-i18next');
var sonner = require('sonner');
var useRolesApi = require('./useRolesApi-DuL4eCuF.js');
var useTeamsApi = require('./useTeamsApi-ClWGPxNW.js');
var formik = require('formik');
var neetoCist = require('@bigbinary/neeto-cist');
var v2_RolesRadioGroup = require('./RolesRadioGroup-BsARnjvF.js');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var jsxRuntime = require('react/jsx-runtime');
var Select = require('./Select-CshPoN2b.js');
var Card = require('@bigbinary/neeto-atoms/primitives/Card');
var constants = require('@bigbinary/neeto-commons-frontend/v2/constants');
var reactUtils = require('@bigbinary/neeto-commons-frontend/v2/react-utils');
var CopyToClipboardButton = require('@bigbinary/neeto-molecules/v2/CopyToClipboardButton');
var useInviteLinksApi = require('./useInviteLinksApi-COVfmZiQ.js');
var formik$1 = require('@bigbinary/neeto-atoms/formik');
var utils$1 = require('./cjs/utils.js');
var neetoTimeZones = require('@bigbinary/neeto-time-zones');
var PhoneNumber = require('@bigbinary/neeto-molecules/v2/PhoneNumber');
var constants$1 = require('./constants-D_H6M1Pm.js');
var ProfileImage = require('./ProfileImage-BLnx0E90.js');
var ActionBlock = require('./ActionBlock-C9Iy0jGZ.js');
var index = require('./index-BOQKf6as.js');
var primitives = require('@bigbinary/neeto-atoms/primitives');
var i18next = require('i18next');
var MoreDropdown = require('@bigbinary/neeto-molecules/v2/MoreDropdown');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _asyncToGenerator__default = /*#__PURE__*/_interopDefault(_asyncToGenerator);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefault(_regeneratorRuntime);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var CopyToClipboardButton__default = /*#__PURE__*/_interopDefault(CopyToClipboardButton);
var i18next__default = /*#__PURE__*/_interopDefault(i18next);
var MoreDropdown__default = /*#__PURE__*/_interopDefault(MoreDropdown);

var _excluded = ["name", "label", "className", "checked", "disabled", "onChange"];
function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var FormikSwitch = function FormikSwitch(_ref) {
  var name = _ref.name,
    label = _ref.label,
    className = _ref.className,
    checkedProp = _ref.checked,
    disabled = _ref.disabled,
    onChangeProp = _ref.onChange,
    rest = _objectWithoutProperties__default.default(_ref, _excluded);
  var _useField = formik.useField(name),
    _useField2 = _slicedToArray__default.default(_useField, 3),
    field = _useField2[0],
    helpers = _useField2[2];
  var isChecked = checkedProp !== undefined ? checkedProp : field.value;
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: neetoAtoms.cn("flex items-center gap-2", className),
    children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Switch, _objectSpread$2({
      disabled: disabled,
      checked: isChecked,
      id: name,
      onCheckedChange: function onCheckedChange(val) {
        helpers.setValue(val);
        onChangeProp === null || onChangeProp === void 0 || onChangeProp({
          target: {
            checked: val
          }
        });
      }
    }, rest)), label && /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Label, {
      htmlFor: name,
      children: label
    })]
  });
};

var _getQueryParams = utils.getQueryParams(),
  page = _getQueryParams.page,
  pageSize = _getQueryParams.pageSize;
var DEFAULT_RADIX = 10;
({
  page: ramda.clamp(1, Infinity, parseInt(page)) || constants.DEFAULT_PAGE_INDEX,
  pageSize: ramda.clamp(10, 100, parseInt(pageSize)) || constants.DEFAULT_PAGE_SIZE});
var DEFAULT_SELECTED_ROWS = {
  active: [],
  emails: [],
  keys: [],
  displayNames: []
};

var AppList = function AppList(_ref) {
  var _globalProps$user;
  var globalRoles = _ref.globalRoles,
    savedStateRef = _ref.savedStateRef;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useState = React.useState(savedStateRef.current.isAppListEnabled),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    isAppListEnabled = _useState2[0],
    setIsAppListEnabled = _useState2[1];
  var _useFormikContext = formik.useFormikContext(),
    _useFormikContext$val = _useFormikContext.values,
    _useFormikContext$val2 = _useFormikContext$val.emails,
    emails = _useFormikContext$val2 === void 0 ? [] : _useFormikContext$val2,
    _useFormikContext$val3 = _useFormikContext$val.appRoles,
    appRoles = _useFormikContext$val3 === void 0 ? [] : _useFormikContext$val3,
    setFieldValue = _useFormikContext.setFieldValue;
  var selectedEmail = ramda.pluck("value", emails);
  var isManageProductsLinkEnabled = ((_globalProps$user = initializers.globalProps.user) === null || _globalProps$user === void 0 ? void 0 : _globalProps$user.isOwner) && Object.keys(globalRoles).length >= 3;
  React.useEffect(function () {
    if (savedStateRef.current.isAppListEnabled !== isAppListEnabled) {
      appRoles === null || appRoles === void 0 || appRoles.forEach(function (appRole, index) {
        var _globalProps$appName;
        if ((appRole === null || appRole === void 0 ? void 0 : appRole.appName) === ((_globalProps$appName = initializers.globalProps.appName) === null || _globalProps$appName === void 0 ? void 0 : _globalProps$appName.substring(5))) {
          setFieldValue("appRoles[".concat(index, "].isEnabled"), true);
          return;
        }
        setFieldValue("appRoles[".concat(index, "].isEnabled"), isAppListEnabled);
      });
    }
    savedStateRef.current.isAppListEnabled = isAppListEnabled;
  }, [isAppListEnabled]); // eslint-disable-line react-hooks/exhaustive-deps

  var buildRoleOptions = function buildRoleOptions(roles) {
    return roles.map(function (role) {
      return neetoCist.toLabelAndValue(role.name);
    });
  };
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "flex flex-col gap-6",
    children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "w-full space-y-3",
      children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "flex items-start gap-2",
        children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Checkbox, {
          checked: isAppListEnabled,
          "data-testid": "ntm-manage-members-app-list-checkbox",
          id: "app-list-toggle",
          onCheckedChange: function onCheckedChange() {
            return setIsAppListEnabled(ramda.not);
          }
        }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Label, {
          className: "leading-relaxed",
          htmlFor: "app-list-toggle",
          children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
            className: "leading-relaxed",
            variant: "body3",
            children: /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
              i18nKey: "neetoTeamMembers.helpers.addMembersToNeetoProducts",
              values: {
                emails: selectedEmail
              }
            })
          })
        })]
      }), isManageProductsLinkEnabled && /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
        variant: "body3",
        children: /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
          i18nKey: "neetoTeamMembers.helpers.manageProducts",
          components: {
            button: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
              asChild: true,
              variant: "link",
              children: /*#__PURE__*/jsxRuntime.jsx("a", {
                href: v2_RolesRadioGroup.NEETO_AUTH_MANAGE_PRODUCT_URL,
                children: "manage"
              })
            })
          }
        })
      })]
    }), /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "w-full",
      children: appRoles.map(function (_ref2, index) {
        var _globalProps$appName2;
        var appName = _ref2.appName,
          isEnabled = _ref2.isEnabled;
        var isCurrentApp = appName === ((_globalProps$appName2 = initializers.globalProps.appName) === null || _globalProps$appName2 === void 0 ? void 0 : _globalProps$appName2.substring(5));
        var isAppRoleSelectionChecked = isCurrentApp || isEnabled;
        return /*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "flex w-full items-center justify-between py-2",
          children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Tooltip, {
            content: isCurrentApp ? t("neetoTeamMembers.tooltips.hostAppIsRequired") : null,
            children: /*#__PURE__*/jsxRuntime.jsx("span", {
              children: /*#__PURE__*/jsxRuntime.jsx(FormikSwitch, {
                checked: isAppRoleSelectionChecked,
                disabled: isCurrentApp,
                name: "appsRoles[".concat(index, "].isEnabled"),
                label: t("neetoTeamMembers.labels.neeto_", {
                  product: appName
                }),
                onChange: function onChange(_ref3) {
                  var target = _ref3.target;
                  setFieldValue("appRoles[".concat(index, "].isEnabled"), target.checked);
                }
              })
            })
          }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Tooltip, {
            content: isCurrentApp ? t("neetoTeamMembers.tooltips.goBackToChangeRole") : null,
            children: /*#__PURE__*/jsxRuntime.jsx("span", {
              className: "w-1/2 max-w-[250px]",
              children: /*#__PURE__*/jsxRuntime.jsx(Select.FormikSelect, {
                isDisabled: isCurrentApp || !isEnabled,
                name: "appRoles[".concat(index, "].activeRole"),
                options: buildRoleOptions(globalRoles[appName])
              })
            })
          })]
        }, appName);
      })
    })]
  });
};

var Confirmation = function Confirmation() {
  var _globalProps$organiza;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useFormikContext = formik.useFormikContext(),
    _useFormikContext$val = _useFormikContext.values,
    emails = _useFormikContext$val.emails,
    role = _useFormikContext$val.role,
    appRoles = _useFormikContext$val.appRoles;
  var selectedEmail = ramda.pluck("value", emails);
  var activeAppRoles = neetoCist.filterBy({
    isEnabled: true
  }, appRoles);
  var isMultipleProduct = activeAppRoles.length > 1;
  return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
    children: [/*#__PURE__*/jsxRuntime.jsx(Card.Card, {
      className: "w-full shrink-0 bg-muted/40 ring-0",
      size: "sm",
      children: /*#__PURE__*/jsxRuntime.jsxs(Card.CardContent, {
        className: "flex items-start gap-3",
        children: [/*#__PURE__*/jsxRuntime.jsx("div", {
          className: "bg-primary/10 mt-0.5 flex size-9 shrink-0 items-center justify-center neeto-ui-rounded-full",
          children: /*#__PURE__*/jsxRuntime.jsx(lucideReact.Mail, {
            className: "size-4 text-primary"
          })
        }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
          className: "min-w-0 flex-1 leading-relaxed",
          variant: "body3",
          children: isMultipleProduct ? /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
            i18nKey: "neetoTeamMembers.helpers.multipleProductInvitation",
            values: {
              count: selectedEmail.length,
              emails: selectedEmail,
              orgName: (_globalProps$organiza = initializers.globalProps.organization) === null || _globalProps$organiza === void 0 ? void 0 : _globalProps$organiza.name
            }
          }) : /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
            i18nKey: "neetoTeamMembers.helpers.singleProductInvitation",
            values: v2_RolesRadioGroup.getSingleInvitationTranslationProps({
              activeAppRoles: activeAppRoles,
              role: role,
              selectedEmail: selectedEmail
            })
          })
        })]
      })
    }), isMultipleProduct && /*#__PURE__*/jsxRuntime.jsx(Card.Card, {
      className: "w-full shrink-0 ring-0",
      size: "sm",
      children: /*#__PURE__*/jsxRuntime.jsx(Card.CardContent, {
        className: "overflow-hidden neeto-ui-rounded-md border border-border p-0",
        children: /*#__PURE__*/jsxRuntime.jsxs("table", {
          className: "w-full border-collapse",
          children: [/*#__PURE__*/jsxRuntime.jsx("thead", {
            className: "bg-muted/40",
            children: /*#__PURE__*/jsxRuntime.jsxs("tr", {
              children: [/*#__PURE__*/jsxRuntime.jsx("th", {
                className: "px-3 py-2 text-start text-xs font-medium uppercase tracking-wide text-muted-foreground",
                children: t("neetoTeamMembers.common.productName")
              }), /*#__PURE__*/jsxRuntime.jsx("th", {
                className: "px-3 py-2 text-start text-xs font-medium uppercase tracking-wide text-muted-foreground",
                children: t("neetoTeamMembers.common.role", constants.SINGULAR)
              })]
            })
          }), /*#__PURE__*/jsxRuntime.jsx("tbody", {
            className: "divide-y divide-border",
            children: activeAppRoles.map(function (_ref) {
              var appName = _ref.appName,
                activeRole = _ref.activeRole;
              return /*#__PURE__*/jsxRuntime.jsxs("tr", {
                children: [/*#__PURE__*/jsxRuntime.jsx("td", {
                  className: "px-3 py-2",
                  children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
                    variant: "body3",
                    children: t("neetoTeamMembers.labels.neeto_", {
                      product: appName
                    })
                  })
                }), /*#__PURE__*/jsxRuntime.jsx("td", {
                  className: "px-3 py-2",
                  children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
                    variant: "body3",
                    children: activeRole
                  })
                })]
              }, appName);
            })
          })]
        })
      })
    })]
  });
};

var InviteLink = function InviteLink(_ref) {
  var _inviteLinks$, _inviteLinks$2, _inviteLinks$3, _inviteLinks$4, _inviteLinks$5, _inviteLinks$6, _inviteLinks$7;
  var t = _ref.t,
    roles = _ref.roles;
  var _useCreateInviteLinks = useInviteLinksApi.useCreateInviteLinks(),
    createInviteLink = _useCreateInviteLinks.mutate,
    isCreateLinkPending = _useCreateInviteLinks.isPending;
  var _useRegenerateInviteL = useInviteLinksApi.useRegenerateInviteLink(),
    regenerateLink = _useRegenerateInviteL.mutate;
  var _useFetchInviteLinks = useInviteLinksApi.useFetchInviteLinks(),
    _useFetchInviteLinks$ = _useFetchInviteLinks.data,
    _useFetchInviteLinks$2 = _useFetchInviteLinks$ === void 0 ? {} : _useFetchInviteLinks$,
    _useFetchInviteLinks$3 = _useFetchInviteLinks$2.inviteLinks,
    inviteLinks = _useFetchInviteLinks$3 === void 0 ? [] : _useFetchInviteLinks$3,
    isFetchLinkLoading = _useFetchInviteLinks.isLoading;
  var _useFormikContext = formik.useFormikContext(),
    values = _useFormikContext.values;
  var _useState = React.useState(""),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    feedbackMessage = _useState2[0],
    setFeedbackMessage = _useState2[1];
  var feedbackTimerRef = React.useRef();
  var showFeedback = function showFeedback(message) {
    setFeedbackMessage(message);
    clearTimeout(feedbackTimerRef.current);
    feedbackTimerRef.current = setTimeout(function () {
      return setFeedbackMessage("");
    }, v2_RolesRadioGroup.FEEDBACK_DURATION_MS);
  };
  React.useEffect(function () {
    return function () {
      return clearTimeout(feedbackTimerRef.current);
    };
  }, []);
  var isInviteLinkEmpty = !isFetchLinkLoading && ramda.isEmpty(inviteLinks);
  var handleRegenerate = function handleRegenerate() {
    var _findBy = neetoCist.findBy({
        name: values.role
      }, roles),
      roleId = _findBy.id;
    if (ramda.isEmpty(inviteLinks)) {
      createInviteLink({
        organizationRoleId: roleId
      }, {
        onSuccess: function onSuccess() {
          return showFeedback(t("neetoTeamMembers.alerts.success.inviteLinkGenerated"));
        }
      });
      return;
    }
    regenerateLink({
      inviteLinkId: inviteLinks[0].id,
      payload: {
        organizationRoleId: roleId
      }
    }, {
      onSuccess: function onSuccess() {
        return showFeedback(t("neetoTeamMembers.alerts.success.inviteLinkRegenerated"));
      }
    });
  };
  if (isFetchLinkLoading || isCreateLinkPending) {
    return /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "flex w-full items-center justify-center",
      children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Spinner, {})
    });
  }
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "w-full space-y-2",
    children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "flex items-center gap-2 pt-1",
      children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "relative flex min-w-0 grow items-center truncate neeto-ui-rounded-md border border-border bg-muted/50 leading-none",
        children: [isInviteLinkEmpty ? /*#__PURE__*/jsxRuntime.jsx("div", {
          className: "relative min-w-0 grow truncate p-2 leading-none"
        }) : /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
          asChild: true,
          className: "relative block h-auto min-w-0 shrink grow truncate p-2 font-normal leading-none no-underline hover:underline",
          variant: "link",
          children: /*#__PURE__*/jsxRuntime.jsx("a", {
            href: v2_RolesRadioGroup.getInviteURL(inviteLinks === null || inviteLinks === void 0 || (_inviteLinks$ = inviteLinks[0]) === null || _inviteLinks$ === void 0 ? void 0 : _inviteLinks$.token),
            rel: "noopener noreferrer",
            target: "_blank",
            children: v2_RolesRadioGroup.getInviteURL(inviteLinks === null || inviteLinks === void 0 || (_inviteLinks$2 = inviteLinks[0]) === null || _inviteLinks$2 === void 0 ? void 0 : _inviteLinks$2.token)
          })
        }), isInviteLinkEmpty ? /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
          className: "rounded-s-none",
          onClick: handleRegenerate,
          children: t("neetoTeamMembers.buttons.generateLink")
        }) : /*#__PURE__*/jsxRuntime.jsx(CopyToClipboardButton__default.default, {
          className: "rounded-s-none border-s",
          value: v2_RolesRadioGroup.getInviteURL(inviteLinks === null || inviteLinks === void 0 || (_inviteLinks$3 = inviteLinks[0]) === null || _inviteLinks$3 === void 0 ? void 0 : _inviteLinks$3.token),
          variant: "ghost"
        })]
      }), !isInviteLinkEmpty && /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.DropdownMenu, {
        customTarget: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
          "aria-label": t("neetoTeamMembers.buttons.regenerateLink"),
          className: "shrink-0",
          icon: lucideReact.EllipsisVertical,
          size: "icon",
          variant: "ghost"
        }),
        children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.DropdownMenu.Menu, {
          children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.DropdownMenu.MenuItem, {
            onClick: handleRegenerate,
            children: t("neetoTeamMembers.buttons.regenerateLink")
          })
        })
      })]
    }), feedbackMessage && /*#__PURE__*/jsxRuntime.jsxs("div", {
      "aria-live": "polite",
      className: "flex w-fit items-center gap-1.5 neeto-ui-rounded-md bg-success-solid px-2 py-1 text-success-solid-foreground animate-in fade-in slide-in-from-top-1 duration-200",
      children: [/*#__PURE__*/jsxRuntime.jsx(lucideReact.Check, {
        className: "size-3.5 shrink-0"
      }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
        color: "inherit",
        variant: "caption",
        weight: "medium",
        children: feedbackMessage
      })]
    }), /*#__PURE__*/jsxRuntime.jsx("div", {
      children: !isInviteLinkEmpty && /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
        className: "leading-relaxed",
        color: "muted",
        variant: "body3",
        children: /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
          components: {
            strong: /*#__PURE__*/jsxRuntime.jsx("strong", {})
          },
          i18nKey: "neetoTeamMembers.alerts.messages.inviteLink",
          values: {
            expiryDays: v2_RolesRadioGroup.remainingExpiryDays(inviteLinks === null || inviteLinks === void 0 || (_inviteLinks$4 = inviteLinks[0]) === null || _inviteLinks$4 === void 0 ? void 0 : _inviteLinks$4.expiresAt),
            role: inviteLinks === null || inviteLinks === void 0 || (_inviteLinks$5 = inviteLinks[0]) === null || _inviteLinks$5 === void 0 || (_inviteLinks$5 = _inviteLinks$5.organizationRole) === null || _inviteLinks$5 === void 0 ? void 0 : _inviteLinks$5.name,
            inviteLimit: inviteLinks === null || inviteLinks === void 0 || (_inviteLinks$6 = inviteLinks[0]) === null || _inviteLinks$6 === void 0 ? void 0 : _inviteLinks$6.inviteLimit,
            appName: initializers.globalProps.appName,
            emailDomain: inviteLinks === null || inviteLinks === void 0 || (_inviteLinks$7 = inviteLinks[0]) === null || _inviteLinks$7 === void 0 ? void 0 : _inviteLinks$7.domain
          }
        })
      })
    })]
  });
};
var InviteLink$1 = reactUtils.withT(InviteLink);

var MultipleEmailInput = function MultipleEmailInput(_ref) {
  var _head;
  var _ref$emails = _ref.emails,
    emails = _ref$emails === void 0 ? [] : _ref$emails,
    innerRef = _ref.innerRef,
    _ref$selectedMember = _ref.selectedMember,
    selectedMember = _ref$selectedMember === void 0 ? null : _ref$selectedMember,
    setCurrentPage = _ref.setCurrentPage;
  var isInviteLinkFeatureEnabled = !utils$1.isNeetoAuthApp();
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useFormikContext = formik.useFormikContext(),
    setFieldValue = _useFormikContext.setFieldValue;
  var handleInputChange = function handleInputChange(event) {
    var email = event.target.value;
    var emailList = [{
      label: email,
      value: email,
      valid: v2_RolesRadioGroup.EMAIL_REGEX.test(email)
    }];
    setFieldValue("emails", emailList);
  };
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: "w-full",
    children: selectedMember ? /*#__PURE__*/jsxRuntime.jsx(formik$1.Input, {
      "data-testid": "ntm-manage-member-email-input",
      name: "emails",
      type: "email",
      value: (_head = ramda.head(emails)) === null || _head === void 0 ? void 0 : _head.value,
      label: /*#__PURE__*/jsxRuntime.jsx("span", {
        className: "flex w-full justify-between",
        children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
          variant: "body3",
          children: t("neetoTeamMembers.common.email", constants.SINGULAR)
        })
      }),
      onChange: handleInputChange
    }) : /*#__PURE__*/jsxRuntime.jsxs("div", {
      children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "flex items-center justify-between pb-2",
        children: [/*#__PURE__*/jsxRuntime.jsxs(neetoAtoms.Label, {
          children: [t("neetoTeamMembers.common.email", constants.PLURAL), /*#__PURE__*/jsxRuntime.jsx("span", {
            className: "text-destructive",
            children: " *"
          })]
        }), isInviteLinkFeatureEnabled && /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
          variant: "link",
          onClick: function onClick() {
            return setCurrentPage(v2_RolesRadioGroup.FORM_PAGES.INVITE_LINK);
          },
          children: t("neetoTeamMembers.buttons.inviteLink")
        })]
      }), /*#__PURE__*/jsxRuntime.jsx(formik$1.MultiEmailInput, {
        required: true,
        counter: v2_RolesRadioGroup.COUNTER_PROPS,
        "data-testid": "ntm-manage-member-email-input",
        filterInvalidEmails: v2_RolesRadioGroup.FILTER_INVALID_EMAILS,
        helpText: t("neetoTeamMembers.helpers.enterMultipleEmails"),
        label: "",
        name: "emails",
        placeholder: t("neetoTeamMembers.placeholders.email"),
        ref: innerRef
      })]
    })
  });
};

var NameInputs = reactUtils.withT(function (_ref) {
  var t = _ref.t,
    innerRef = _ref.innerRef;
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "flex w-full gap-4",
    children: [/*#__PURE__*/jsxRuntime.jsx(formik$1.Input, {
      "data-testid": "ntm-edit-member-first-name-text-field",
      label: t("neetoTeamMembers.labels.firstName"),
      name: "firstName",
      ref: innerRef
    }), /*#__PURE__*/jsxRuntime.jsx(formik$1.Input, {
      "data-testid": "ntm-edit-member-last-name-text-field",
      label: t("neetoTeamMembers.labels.lastName"),
      name: "lastName"
    })]
  });
});

var ProfileSettings = function ProfileSettings(_ref) {
  var member = _ref.member,
    setFieldValue = _ref.setFieldValue,
    isTimezoneFieldDisabled = _ref.isTimezoneFieldDisabled;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var setFieldValueRef = React.useRef(setFieldValue);
  React.useEffect(function () {
    setFieldValueRef.current = setFieldValue;
  }, [setFieldValue]);
  var _useCountries = ProfileImage.useCountries(),
    countryDropdownOptions = _useCountries.countryDropdownOptions,
    isFetchingCountriesList = _useCountries.isFetchingCountriesList,
    handleCountryChange = _useCountries.handleCountryChange;
  var timezoneContainerRef = React.useCallback(function (node) {
    if (ramda.isNotNil(node)) {
      new neetoTimeZones.NeetoTimezoneSelector(node, {
        isTimeFormat24H: member.timeFormat === "24h",
        className: "w-full z-10",
        position: "bottom",
        initialValue: member.timeZone,
        onChange: function onChange(_ref2) {
          var main = _ref2.main;
          return setFieldValueRef.current("timeZone", main);
        },
        disabled: isTimezoneFieldDisabled
      });
    }
  }, [member.timeZone, member.timeFormat, isTimezoneFieldDisabled]);
  React.useEffect(function () {
    var country = neetoCist.findBy({
      value: member.countryIdentifier
    }, countryDropdownOptions);
    if (country) handleCountryChange(country);
  }, [member.countryIdentifier, countryDropdownOptions, handleCountryChange]);
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "w-full space-y-6",
    "data-cy": "ntm-profile-settings",
    children: [/*#__PURE__*/jsxRuntime.jsx(PhoneNumber.FormikPhoneNumberInput, {
      "data-cy": "ntm-edit-member-phonenumber-field",
      label: t("neetoTeamMembers.profile.inputs.label.phonenumber"),
      name: "phonenumber"
    }), /*#__PURE__*/jsxRuntime.jsx(Select.FormikSelect, {
      "data-cy": "ntm-edit-member-country-select",
      isLoading: isFetchingCountriesList,
      label: t("neetoTeamMembers.profile.inputs.label.country"),
      name: "countryId",
      options: countryDropdownOptions,
      onChange: function onChange(value) {
        var option = countryDropdownOptions.find(function (o) {
          return o.value === value;
        });
        var dependentFields = handleCountryChange(option);
        setFieldValue("dateFormat", dependentFields === null || dependentFields === void 0 ? void 0 : dependentFields.dateFormat);
      }
    }), /*#__PURE__*/jsxRuntime.jsx(Select.FormikSelect, {
      "data-cy": "ntm-edit-member-language-select",
      label: t("neetoTeamMembers.profile.inputs.label.language"),
      name: "language",
      options: constants.LANGUAGE_OPTIONS
    }), /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "space-y-2",
      children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Label, {
        children: t("neetoTeamMembers.profile.inputs.label.timeZone")
      }), /*#__PURE__*/jsxRuntime.jsx("div", {
        "data-cy": "ntm-edit-member-timezone-select",
        ref: timezoneContainerRef,
        className: neetoAtoms.cn("w-full grow", {
          "pointer-events-none bg-muted": isTimezoneFieldDisabled
        })
      })]
    }), /*#__PURE__*/jsxRuntime.jsx(Select.FormikSelect, {
      "data-cy": "ntm-edit-member-time-format-select",
      label: t("neetoTeamMembers.profile.inputs.label.preferredTimeFormat"),
      name: "timeFormat",
      options: constants$1.TIME_FORMAT_OPTIONS
    }), /*#__PURE__*/jsxRuntime.jsx(Select.FormikSelect, {
      "data-cy": "ntm-edit-member-date-format-select",
      label: t("neetoTeamMembers.profile.inputs.label.preferredDateFormat"),
      name: "dateFormat",
      options: constants$1.DATE_FORMAT_OPTIONS
    })]
  });
};

function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var renderNameColumn = function renderNameColumn(_ref) {
  var config = _ref.config,
    handleUpdateRole = _ref.handleUpdateRole,
    handleUpdateStatus = _ref.handleUpdateStatus,
    tableData = _ref.tableData;
  var name = tableData.displayName,
    imageUrl = tableData.profileImageUrl;
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "flex w-full justify-between gap-3",
    children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "flex items-center gap-2",
      children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Avatar, {
        className: "size-8",
        user: {
          name: name,
          imageUrl: imageUrl
        }
      }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
        className: "whitespace-normal",
        "data-testid": "ntm-member-name-".concat(utils.hyphenize(name)),
        variant: "body3",
        children: name
      })]
    }), renderDropdownButton({
      config: config,
      handleUpdateRole: handleUpdateRole,
      handleUpdateStatus: handleUpdateStatus,
      tableData: tableData
    })]
  });
};
var renderDropdownButton = function renderDropdownButton(_ref2) {
  var _config$table, _config$table$dropdow;
  var config = _ref2.config,
    handleUpdateRole = _ref2.handleUpdateRole,
    handleUpdateStatus = _ref2.handleUpdateStatus,
    tableData = _ref2.tableData;
  return /*#__PURE__*/jsxRuntime.jsx(MoreDropdown__default.default, {
    isDisabled: ramda.not(config.permissions.update),
    dropdownButtonProps: {
      "data-testid": "ntm-members-table-row-dropdown-button",
      tooltipProps: {
        content: i18next__default.default.t("neetoTeamMembers.tooltips.noPermissionToEditMembers"),
        disabled: config.permissions.update,
        position: "top"
      }
    },
    menuTopChildren: /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
      children: [/*#__PURE__*/jsxRuntime.jsx(primitives.DropdownMenuItem, {
        className: "cursor-pointer",
        "data-testid": "ntm-edit-member-button",
        onClick: function onClick() {
          return handleUpdateRole(tableData);
        },
        children: i18next__default.default.t("neetoTeamMembers.common.edit")
      }), config === null || config === void 0 || (_config$table = config.table) === null || _config$table === void 0 || (_config$table$dropdow = _config$table.dropdownProps) === null || _config$table$dropdow === void 0 ? void 0 : _config$table$dropdow.call(_config$table, tableData), /*#__PURE__*/jsxRuntime.jsx(primitives.DropdownMenuItem, {
        className: "cursor-pointer",
        "data-testid": "ntm-deactivate-member-button",
        onClick: function onClick() {
          return handleUpdateStatus(tableData);
        },
        children: i18next__default.default.t("neetoTeamMembers.common.remove")
      })]
    })
  });
};
var getDefaultAlertTitle = function getDefaultAlertTitle(_ref3) {
  var member = _ref3.member;
  return member !== null && member !== void 0 && member.active ? i18next__default.default.t("neetoTeamMembers.common.remove_", {
    what: initializers.taxonomies.member.singular
  }) : i18next__default.default.t("neetoTeamMembers.common.activate_", {
    what: initializers.taxonomies.member.singular
  });
};
var getDefaultAlertMessage = function getDefaultAlertMessage(_ref4) {
  var member = _ref4.member;
  return /*#__PURE__*/jsxRuntime.jsx(reactI18next.Trans, {
    i18nKey: "neetoTeamMembers.alerts.messages.removeMember",
    values: _objectSpread$1(_objectSpread$1({}, constants.SINGULAR), {}, {
      person: member === null || member === void 0 ? void 0 : member.displayName
    })
  });
};
var getDefaultColumns = function getDefaultColumns(_ref5) {
  var config = _ref5.config,
    handleUpdateRole = _ref5.handleUpdateRole,
    handleUpdateStatus = _ref5.handleUpdateStatus,
    otherColumns = _ref5.otherColumns,
    isSize = _ref5.isSize;
  return [{
    accessorKey: "name",
    id: "name",
    size: 300,
    enablePinning: neetoCist.isNotEmpty(otherColumns) && !isSize("mobile"),
    cell: function cell(_ref6) {
      var row = _ref6.row;
      return renderNameColumn({
        config: config,
        handleUpdateRole: handleUpdateRole,
        handleUpdateStatus: handleUpdateStatus,
        tableData: row.original
      });
    },
    enableSorting: true,
    header: i18next__default.default.t("neetoTeamMembers.common.name"),
    enableHiding: false
  }, {
    accessorKey: "email",
    id: "email",
    enableSorting: true,
    size: 350,
    header: i18next__default.default.t("neetoTeamMembers.common.email", constants.SINGULAR)
  }, {
    accessorKey: "role",
    enableSorting: true,
    size: 200,
    header: i18next__default.default.t("neetoTeamMembers.common.role", constants.SINGULAR)
  }];
};
var removeExcludedRole = ramda.curry(function (excludedRoles, role) {
  return !(excludedRoles !== null && excludedRoles !== void 0 && excludedRoles.includes(role === null || role === void 0 ? void 0 : role.name));
});
var getColumnData = function getColumnData(_ref7) {
  var _config$otherColumns;
  var config = _ref7.config,
    handleUpdateRole = _ref7.handleUpdateRole,
    handleUpdateStatus = _ref7.handleUpdateStatus,
    isSize = _ref7.isSize;
  var otherColumns = (_config$otherColumns = config === null || config === void 0 ? void 0 : config.otherColumns) !== null && _config$otherColumns !== void 0 ? _config$otherColumns : [];
  var defaultColumns = getDefaultColumns({
    config: config,
    handleUpdateRole: handleUpdateRole,
    handleUpdateStatus: handleUpdateStatus,
    otherColumns: otherColumns,
    isSize: isSize
  });
  var columns = defaultColumns.map(function (column) {
    var otherColumn = otherColumns.find(function (col) {
      return ramda.identical(col.accessorKey || col.id, column.accessorKey || column.id);
    });
    return otherColumn || column;
  });
  otherColumns.forEach(function (otherColumn) {
    var key = otherColumn.accessorKey || otherColumn.id;
    var exists = columns.find(function (col) {
      return ramda.identical(col.accessorKey || col.id, key);
    });
    if (!exists) columns.push(otherColumn);
  });
  return columns;
};
var renderUpdateAlert = function renderUpdateAlert(field, props) {
  var _config$alert;
  var config = props.config,
    member = props.member;
  if (config !== null && config !== void 0 && (_config$alert = config.alert) !== null && _config$alert !== void 0 && _config$alert[field]) {
    var _config$alert2;
    return (_config$alert2 = config.alert) === null || _config$alert2 === void 0 ? void 0 : _config$alert2[field]({
      active: member === null || member === void 0 ? void 0 : member.active,
      id: member === null || member === void 0 ? void 0 : member.id,
      name: member === null || member === void 0 ? void 0 : member.displayName
    });
  }
  return field === "title" ? getDefaultAlertTitle(props) : getDefaultAlertMessage(props);
};
var handlePageChange = function handlePageChange(setFilters, history) {
  return function (page, pageSize) {
    var searchParams = utils.getQueryParams({
      toCamelCase: false
    });
    history.replace(utils.buildUrl(window.location.pathname, ramda.mergeLeft({
      page: page,
      page_size: pageSize
    }, searchParams)));
    setFilters(ramda.mergeLeft({
      page: page,
      pageSize: pageSize
    }));
  };
};
var getFilteredRoles = function getFilteredRoles() {
  var roles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  return ramda.filter(removeExcludedRole(config === null || config === void 0 ? void 0 : config.excludedRoles), roles);
};
var generateNoDataContent = function generateNoDataContent(_ref9) {
  var buttonProps = _ref9.buttonProps;
  var disabled = buttonProps.disabled,
    onClick = buttonProps.onClick;
  var noDataTitle = i18next__default.default.t("neetoTeamMembers.common.memberEmptyTitle", {
    what: initializers.taxonomies.member.plural
  });
  var noDataDescription = i18next__default.default.t("neetoTeamMembers.common.memberEmptyDescription", {
    what: initializers.taxonomies.member.plural
  });
  var noDataButtonProps = {
    "data-testid": "ntm-add-member-button",
    disabled: disabled,
    label: i18next__default.default.t("neetoTeamMembers.common.addNew_", {
      what: initializers.taxonomies.member.singular
    }),
    onClick: onClick
  };
  return {
    noDataTitle: noDataTitle,
    noDataDescription: noDataDescription,
    noDataIcon: lucideReact.Users,
    noDataButtonProps: noDataButtonProps
  };
};

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var ManageMember = function ManageMember(_ref) {
  var _manageMemberComponen, _config$additionalFie2;
  var config = _ref.config,
    onComplete = _ref.onComplete,
    _ref$roles = _ref.roles,
    roles = _ref$roles === void 0 ? [] : _ref$roles,
    _ref$selectedMember = _ref.selectedMember,
    selectedMember = _ref$selectedMember === void 0 ? null : _ref$selectedMember,
    _ref$componentConfig = _ref.componentConfig,
    componentConfig = _ref$componentConfig === void 0 ? {} : _ref$componentConfig;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useState = React.useState(false),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    isCreationStatusPollingEnabled = _useState2[0],
    setIsCreationStatusPollingEnabled = _useState2[1];
  var isViewPermissionGranted = config.permissions.view;
  var isNotDevelopment = initializers.globalProps.railsEnv !== "development";
  var _useFetchMembers = useTeamsApi.useFetchMembers({
      enabled: isViewPermissionGranted
    }),
    team = _useFetchMembers.data;
  var _useFetchMember = useTeamsApi.useFetchMember(selectedMember === null || selectedMember === void 0 ? void 0 : selectedMember.id, {
      enabled: !!selectedMember
    }),
    memberShowData = _useFetchMember.data,
    isMemberDetailLoading = _useFetchMember.isLoading;
  var isTimezoneFieldDisabled = selectedMember && memberShowData && !selectedMember.isOwner && !memberShowData.timezoneChangeEnabled;
  var _useState3 = React.useState(v2_RolesRadioGroup.FORM_PAGES.MAIN),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    currentPage = _useState4[0],
    setCurrentPage = _useState4[1];
  var formReference = React.useRef(null);
  var inputReference = React.useRef(null);
  var appListSavedStateReference = React.useRef({
    isAppListEnabled: true
  });
  var shouldSkipAppListPage = React.useRef(false);
  var formikValues = React.useRef(null);
  var manageMemberComponentConfig = _objectSpread(_objectSpread({}, v2_RolesRadioGroup.DEFAULT_COMPONENT_CONFIG), {}, {
    initialFocusRef: inputReference
  }, componentConfig);
  var Component = v2_RolesRadioGroup.MEMBERS_FORM_COMPONENT_MAPPER[manageMemberComponentConfig.type || "pane"];
  var haveToFetchRoles = ramda.isEmpty(roles) && isViewPermissionGranted;
  var isEditForm = !!selectedMember;
  var isLastPage = currentPage === v2_RolesRadioGroup.FORM_PAGES.CONFIRMATION || isEditForm;
  var _useFetchRoles = useRolesApi.useFetchRoles({
      select: function select(response) {
        var _response$organizatio;
        return ramda.reverse((_response$organizatio = response.organizationRoles) !== null && _response$organizatio !== void 0 ? _response$organizatio : []);
      },
      enabled: haveToFetchRoles
    }),
    _useFetchRoles$data = _useFetchRoles.data,
    rolesList = _useFetchRoles$data === void 0 ? roles : _useFetchRoles$data,
    isRolesLoading = _useFetchRoles.isLoading;
  var _useFetchGlobalRoles = useRolesApi.useFetchGlobalRoles({
      select: function select(response) {
        return ramda.groupBy(ramda.prop("appName"), response !== null && response !== void 0 ? response : []);
      },
      enabled: isNotDevelopment && !selectedMember && isViewPermissionGranted
    }),
    _useFetchGlobalRoles$ = _useFetchGlobalRoles.data,
    globalRoles = _useFetchGlobalRoles$ === void 0 ? {} : _useFetchGlobalRoles$,
    isGlobalRolesLoading = _useFetchGlobalRoles.isLoading;
  var filteredRoles = getFilteredRoles(rolesList, config);
  var _useCreateMember = useTeamsApi.useCreateMember({
      onSuccess: function onSuccess() {
        return setIsCreationStatusPollingEnabled(true);
      }
    }),
    _useCreateMember$data = _useCreateMember.data,
    _useCreateMember$data2 = _useCreateMember$data === void 0 ? {} : _useCreateMember$data,
    jobId = _useCreateMember$data2.jobId,
    createMember = _useCreateMember.mutate,
    isCreatingMember = _useCreateMember.isPending;
  var refetchInterval = function refetchInterval(query) {
    var _ref2 = query.state.data || {},
      isCompleted = _ref2.isCompleted;
    if (isCompleted) {
      setIsCreationStatusPollingEnabled(false);
      return false;
    }
    return 2000;
  };
  var _useMembersCreationSt = useTeamsApi.useMembersCreationStatus(jobId, {
      refetchInterval: refetchInterval,
      enabled: isCreationStatusPollingEnabled && !!jobId
    }),
    creationStatus = _useMembersCreationSt.data;
  React.useEffect(function () {
    var _config$createMember;
    var _ref3 = creationStatus || {},
      isCompleted = _ref3.isCompleted,
      isSuccessful = _ref3.isSuccessful,
      users = _ref3.users,
      error = _ref3.error;
    if (!isCompleted) return;
    handleClose();
    config === null || config === void 0 || (_config$createMember = config.createMember) === null || _config$createMember === void 0 || (_config$createMember = _config$createMember.onSuccess) === null || _config$createMember === void 0 || _config$createMember.callback({
      users: users
    });
    if (isSuccessful) {
      utils.showThumbsUpToastr();
    } else {
      sonner.toast.error(error);
    }
    useTeamsApi.refetchMembers();
  }, [creationStatus]);
  var _useUpdateMember = useTeamsApi.useUpdateMember({
      onSuccess: function onSuccess() {
        var _config$updateMember, _globalProps$user;
        handleClose(true);
        config === null || config === void 0 || (_config$updateMember = config.updateMember) === null || _config$updateMember === void 0 || (_config$updateMember = _config$updateMember.onSuccess) === null || _config$updateMember === void 0 || _config$updateMember.callback();
        if ((selectedMember === null || selectedMember === void 0 ? void 0 : selectedMember.id) === ((_globalProps$user = initializers.globalProps.user) === null || _globalProps$user === void 0 ? void 0 : _globalProps$user.id)) {
          window.location.reload();
        }
      }
    }),
    updateMember = _useUpdateMember.mutate,
    isUpdatingMember = _useUpdateMember.isPending;
  var hasRoleChanged = function hasRoleChanged(_ref4) {
    var submitted = _ref4.submitted,
      values = _ref4.values;
    return submitted && (values === null || values === void 0 ? void 0 : values.role) !== (selectedMember === null || selectedMember === void 0 ? void 0 : selectedMember.role);
  };
  var handleClose = function handleClose() {
    var submitted = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    onComplete({
      submitted: hasRoleChanged({
        submitted: submitted,
        values: formikValues.current
      })
    });
    setCurrentPage(v2_RolesRadioGroup.FORM_PAGES.MAIN);
    appListSavedStateReference.current = {
      isAppListEnabled: true
    };
    setIsCreationStatusPollingEnabled(false);
  };
  var _useProfileImageUploa = hooks.useProfileImageUpload({
      uploadConfig: {
        folder: "Auth",
        customMetadata: {
          appName: "neetoAuth"
        }
      }
    }),
    uploadImage = _useProfileImageUploa.uploadImage,
    isUploading = _useProfileImageUploa.isUploading;
  var handleUploadImage = /*#__PURE__*/function () {
    var _ref5 = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee(image) {
      var result;
      return _regeneratorRuntime__default.default.wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return uploadImage(image, function (uploadedImageData) {
              result = uploadedImageData;
            });
          case 2:
            return _context.abrupt("return", result);
          case 3:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function handleUploadImage(_x) {
      return _ref5.apply(this, arguments);
    };
  }();
  var isProcessing = isCreatingMember || isUpdatingMember || isUploading || isRolesLoading || isGlobalRolesLoading || isMemberDetailLoading;
  var handleAddMember = /*#__PURE__*/function () {
    var _ref6 = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee2(values) {
      var _values$avatar, payload, _yield$handleUploadIm, fileId, filePath, url;
      return _regeneratorRuntime__default.default.wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            if (!selectedMember) {
              _context2.next = 25;
              break;
            }
            payload = v2_RolesRadioGroup.renderPayload(values, selectedMember);
            if (!((_values$avatar = values.avatar) !== null && _values$avatar !== void 0 && _values$avatar.file)) {
              _context2.next = 22;
              break;
            }
            if (!payload.profile) payload.profile = {};
            if (!(values.avatar.file === "_destroy")) {
              _context2.next = 8;
              break;
            }
            payload.profile.avatar = {
              fileId: "_destroy",
              filePath: "",
              url: ""
            };
            _context2.next = 22;
            break;
          case 8:
            _context2.prev = 8;
            _context2.next = 11;
            return handleUploadImage(values.avatar.file);
          case 11:
            _yield$handleUploadIm = _context2.sent;
            fileId = _yield$handleUploadIm.fileId;
            filePath = _yield$handleUploadIm.filePath;
            url = _yield$handleUploadIm.url;
            payload.profile.avatar = {
              fileId: fileId,
              filePath: filePath,
              url: url
            };
            _context2.next = 22;
            break;
          case 18:
            _context2.prev = 18;
            _context2.t0 = _context2["catch"](8);
            sonner.toast.error(_context2.t0.message);
            return _context2.abrupt("return");
          case 22:
            updateMember({
              id: selectedMember.id,
              payload: payload
            });
            _context2.next = 26;
            break;
          case 25:
            createMember(v2_RolesRadioGroup.renderPayload(values));
          case 26:
          case "end":
            return _context2.stop();
        }
      }, _callee2, null, [[8, 18]]);
    }));
    return function handleAddMember(_x2) {
      return _ref6.apply(this, arguments);
    };
  }();
  var handleOnSubmit = /*#__PURE__*/function () {
    var _ref8 = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee3(values, _ref7) {
      var setSubmitting;
      return _regeneratorRuntime__default.default.wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            setSubmitting = _ref7.setSubmitting;
            shouldSkipAppListPage.current = ramda.isEmpty(values.appRoles);
            if (!isLastPage) {
              _context3.next = 7;
              break;
            }
            _context3.next = 5;
            return handleAddMember(values);
          case 5:
            _context3.next = 8;
            break;
          case 7:
            if (currentPage === v2_RolesRadioGroup.FORM_PAGES.APP_LIST || shouldSkipAppListPage.current) {
              setCurrentPage(v2_RolesRadioGroup.FORM_PAGES.CONFIRMATION);
              setSubmitting(false);
            } else if (currentPage === v2_RolesRadioGroup.FORM_PAGES.MAIN) {
              setCurrentPage(v2_RolesRadioGroup.FORM_PAGES.APP_LIST);
              setSubmitting(false);
            }
          case 8:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }));
    return function handleOnSubmit(_x3, _x4) {
      return _ref8.apply(this, arguments);
    };
  }();
  var handleBackButton = function handleBackButton() {
    if (currentPage === v2_RolesRadioGroup.FORM_PAGES.APP_LIST || shouldSkipAppListPage.current || currentPage === v2_RolesRadioGroup.FORM_PAGES.INVITE_LINK) {
      setCurrentPage(v2_RolesRadioGroup.FORM_PAGES.MAIN);
    } else if (currentPage === v2_RolesRadioGroup.FORM_PAGES.CONFIRMATION) {
      setCurrentPage(v2_RolesRadioGroup.FORM_PAGES.APP_LIST);
    }
  };
  var getTitle = function getTitle() {
    var memberLabel = initializers.taxonomies.member.singular;
    if (selectedMember) {
      return t("neetoTeamMembers.common.edit_", {
        what: memberLabel
      });
    }
    return currentPage === v2_RolesRadioGroup.FORM_PAGES.INVITE_LINK ? t("neetoTeamMembers.common.inviteViaLink") : t("neetoTeamMembers.common.addNew_", {
      what: memberLabel
    });
  };
  var renderRolesRadioGroup = function renderRolesRadioGroup(role) {
    return /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "w-full pt-2",
      children: /*#__PURE__*/jsxRuntime.jsx(v2_RolesRadioGroup.RolesRadioGroup, {
        config: config,
        globalRoles: globalRoles,
        role: role,
        isEdit: !!selectedMember,
        roles: filteredRoles
      })
    });
  };
  var renderFormPage = function renderFormPage(page, emails, role, setFieldValue) {
    var _memberShowData$membe, _memberShowData$membe2, _config$additionalFie;
    switch (page) {
      case v2_RolesRadioGroup.FORM_PAGES.MAIN:
        return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
          children: [selectedMember && /*#__PURE__*/jsxRuntime.jsx(ProfileImage.ProfileImage, {}), selectedMember && /*#__PURE__*/jsxRuntime.jsx(NameInputs, {
            innerRef: inputReference
          }), /*#__PURE__*/jsxRuntime.jsx(MultipleEmailInput, {
            emails: emails,
            selectedMember: selectedMember,
            setCurrentPage: setCurrentPage,
            innerRef: inputReference
          }), selectedMember && /*#__PURE__*/jsxRuntime.jsx(ProfileSettings, {
            isTimezoneFieldDisabled: isTimezoneFieldDisabled,
            setFieldValue: setFieldValue,
            member: _objectSpread(_objectSpread({}, selectedMember), {}, {
              countryIdentifier: (_memberShowData$membe = memberShowData === null || memberShowData === void 0 || (_memberShowData$membe2 = memberShowData.member) === null || _memberShowData$membe2 === void 0 ? void 0 : _memberShowData$membe2.countryIdentifier) !== null && _memberShowData$membe !== void 0 ? _memberShowData$membe : selectedMember.countryIdentifier
            })
          }), renderRolesRadioGroup(role), (_config$additionalFie = config.additionalFields) === null || _config$additionalFie === void 0 ? void 0 : _config$additionalFie.component]
        });
      case v2_RolesRadioGroup.FORM_PAGES.APP_LIST:
        return /*#__PURE__*/jsxRuntime.jsx(AppList, {
          globalRoles: globalRoles,
          savedStateRef: appListSavedStateReference
        });
      case v2_RolesRadioGroup.FORM_PAGES.CONFIRMATION:
        return /*#__PURE__*/jsxRuntime.jsx(Confirmation, {});
      case v2_RolesRadioGroup.FORM_PAGES.INVITE_LINK:
        return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
          children: [/*#__PURE__*/jsxRuntime.jsx(InviteLink$1, {
            roles: filteredRoles
          }), renderRolesRadioGroup(role)]
        });
      default:
        return null;
    }
  };
  var isSheet = manageMemberComponentConfig.type !== "modal";
  return /*#__PURE__*/jsxRuntime.jsxs(Component, {
    "data-testid": "ntm-manage-members-pane-wrapper",
    isOpen: manageMemberComponentConfig.isOpen,
    className: classnames__default.default("ntm-timezone-shadcn-overrides", manageMemberComponentConfig.className),
    onClose: function onClose() {
      return handleClose(false);
    },
    children: [/*#__PURE__*/jsxRuntime.jsxs(Component.Header, _objectSpread(_objectSpread({}, isSheet ? manageMemberComponentConfig.headerProps : {}), {}, {
      className: neetoAtoms.cn(isSheet && currentPage !== v2_RolesRadioGroup.FORM_PAGES.MAIN && "flex flex-row items-center gap-2", isSheet && ((_manageMemberComponen = manageMemberComponentConfig.headerProps) === null || _manageMemberComponen === void 0 ? void 0 : _manageMemberComponen.className)),
      children: [isSheet && currentPage !== v2_RolesRadioGroup.FORM_PAGES.MAIN && /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
        "aria-label": t("neetoTeamMembers.buttons.back"),
        icon: lucideReact.ArrowLeft,
        size: "icon-sm",
        variant: "ghost",
        onClick: handleBackButton
      }), /*#__PURE__*/jsxRuntime.jsxs("div", {
        children: [/*#__PURE__*/jsxRuntime.jsx(Component.Title, {
          "data-testid": "ntm-manage-members-pane-header",
          children: getTitle()
        }), selectedMember && Component.Description && /*#__PURE__*/jsxRuntime.jsx(Component.Description, {
          children: t("neetoTeamMembers.helpers.editPaneSubtitle")
        })]
      })]
    })), /*#__PURE__*/jsxRuntime.jsx(Select.FormikForm, {
      ref: formReference,
      className: classnames__default.default({
        "flex flex-1 flex-col overflow-hidden": isSheet
      }),
      formikProps: {
        enableReinitialize: true,
        initialValues: v2_RolesRadioGroup.renderInitialValues({
          additionalFieldsInitialValues: (_config$additionalFie2 = config.additionalFields) === null || _config$additionalFie2 === void 0 ? void 0 : _config$additionalFie2.initialValues,
          globalRoles: globalRoles,
          memberShowData: memberShowData,
          roles: filteredRoles,
          selectedMember: selectedMember
        }),
        onSubmit: handleOnSubmit,
        validationSchema: v2_RolesRadioGroup.buildValidationSchema(_objectSpread({
          selectedMember: selectedMember
        }, team))
      },
      children: function children(_ref9) {
        var _manageMemberComponen2, _manageMemberComponen3;
        var values = _ref9.values,
          isValid = _ref9.isValid,
          dirty = _ref9.dirty,
          setFieldValue = _ref9.setFieldValue;
        var emails = values.emails,
          role = values.role;
        formikValues.current = values;
        return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
          children: [/*#__PURE__*/jsxRuntime.jsx(index.ScrollToErrorField, {
            formRef: formReference
          }), /*#__PURE__*/jsxRuntime.jsxs("div", _objectSpread(_objectSpread({}, isSheet ? manageMemberComponentConfig.bodyProps : {}), {}, {
            className: neetoAtoms.cn(isSheet ? "w-full flex-1 space-y-6 overflow-y-auto px-6 pb-4" : "w-full space-y-6 pb-4", isSheet && ((_manageMemberComponen2 = manageMemberComponentConfig.bodyProps) === null || _manageMemberComponen2 === void 0 ? void 0 : _manageMemberComponen2.className)),
            children: [isSheet && isCreationStatusPollingEnabled && /*#__PURE__*/jsxRuntime.jsxs(neetoAtoms.Alert, {
              children: [/*#__PURE__*/jsxRuntime.jsx(lucideReact.Info, {
                className: "size-4"
              }), /*#__PURE__*/jsxRuntime.jsxs(neetoAtoms.Alert.Title, {
                className: "flex items-center gap-2",
                children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Spinner, {}), t("neetoTeamMembers.helpers.memberCreationStatus", {
                  count: emails.length
                })]
              })]
            }), renderFormPage(currentPage, emails, role, setFieldValue)]
          })), currentPage !== v2_RolesRadioGroup.FORM_PAGES.INVITE_LINK && /*#__PURE__*/jsxRuntime.jsx(Component.Footer, _objectSpread(_objectSpread({}, isSheet ? manageMemberComponentConfig.footerProps : {}), {}, {
            className: neetoAtoms.cn("flex gap-2", isSheet && ((_manageMemberComponen3 = manageMemberComponentConfig.footerProps) === null || _manageMemberComponen3 === void 0 ? void 0 : _manageMemberComponen3.className)),
            children: /*#__PURE__*/jsxRuntime.jsx(ActionBlock.FormikActionBlock, {
              cancelButtonProps: {
                "data-testid": "ntm-manage-member-cancel-button",
                onClick: function onClick() {
                  return handleClose(false);
                }
              },
              isSubmitting: isProcessing || isCreationStatusPollingEnabled,
              submitButtonProps: {
                "data-testid": isLastPage ? "ntm-manage-member-submit-button" : "ntm-manage-member-continue-button",
                label: isLastPage ? t("neetoTeamMembers.buttons.saveChanges") : t("neetoTeamMembers.buttons.continue"),
                disabled: !isValid || isProcessing || !dirty || isCreationStatusPollingEnabled
              }
            })
          }))]
        });
      }
    })]
  });
};

exports.DEFAULT_RADIX = DEFAULT_RADIX;
exports.DEFAULT_SELECTED_ROWS = DEFAULT_SELECTED_ROWS;
exports.ManageMember = ManageMember;
exports.generateNoDataContent = generateNoDataContent;
exports.getColumnData = getColumnData;
exports.getFilteredRoles = getFilteredRoles;
exports.handlePageChange = handlePageChange;
exports.renderUpdateAlert = renderUpdateAlert;
//# sourceMappingURL=index-D0px8LnB.js.map
