import {
  Container
} from "./chunk-6ZN4ZDRA.mjs";
import {
  AddedMemberCard_default
} from "./chunk-J5RBSTY7.mjs";
import {
  DEFAULT_FORM_VALIDATION
} from "./chunk-SHAYA2Y4.mjs";
import {
  SearchbarContainer
} from "./chunk-NDITP7OC.mjs";
import {
  AddMemberCard_default
} from "./chunk-7KWOCW5S.mjs";
import {
  GroupChatMembersList_default
} from "./chunk-PCNJUF7N.mjs";
import {
  CREATE_OR_EDIT_GROUP_FORM_VALUE,
  DEFAULT_CREATE_OR_EDIT_GROUP_FORM_VALUE
} from "./chunk-H5NG76GK.mjs";
import {
  useUpdateChatRoomMutation
} from "./chunk-VRKA22N5.mjs";
import {
  useAllProfilesList
} from "./chunk-74JK7EXM.mjs";

// tmp-babel/messages/web/GroupChatEdit/AddMembersMobile/index.js
import { useMemo } from "react";
import { IconButton } from "@baseapp-frontend/design-system/components/web/buttons";
import { CheckMarkIcon } from "@baseapp-frontend/design-system/components/web/icons";
import { Iconify } from "@baseapp-frontend/design-system/components/web/images";
import { setFormRelayErrors, useNotification } from "@baseapp-frontend/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { Box, Typography } from "@mui/material";
import { useForm } from "react-hook-form";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
function _typeof(o) {
  "@babel/helpers - typeof";
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof(o);
}
function ownKeys(e, r) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r && (o = o.filter(function(r2) {
      return Object.getOwnPropertyDescriptor(e, r2).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(r2) {
      _defineProperty(e, r2, t[r2]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) {
      Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
    });
  }
  return e;
}
function _defineProperty(e, r, t) {
  return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e;
}
function _toPropertyKey(t) {
  var i = _toPrimitive(t, "string");
  return "symbol" == _typeof(i) ? i : i + "";
}
function _toPrimitive(t, r) {
  if ("object" != _typeof(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r || "default");
    if ("object" != _typeof(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r ? String : Number)(t);
}
function _toConsumableArray(r) {
  return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
}
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArray(r) {
  if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
}
function _arrayWithoutHoles(r) {
  if (Array.isArray(r)) return _arrayLikeToArray(r);
}
function _slicedToArray(r, e) {
  return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(r, a) {
  if (r) {
    if ("string" == typeof r) return _arrayLikeToArray(r, a);
    var t = {}.toString.call(r).slice(8, -1);
    return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  }
}
function _arrayLikeToArray(r, a) {
  (null == a || a > r.length) && (a = r.length);
  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  return n;
}
function _iterableToArrayLimit(r, l) {
  var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (null != t) {
    var e, n, i, u, a = [], f = true, o = false;
    try {
      if (i = (t = t.call(r)).next, 0 === l) {
        if (Object(t) !== t) return;
        f = false;
      } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = true) ;
    } catch (r2) {
      o = true, n = r2;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a;
  }
}
function _arrayWithHoles(r) {
  if (Array.isArray(r)) return r;
}
var AddMembersMobile = function AddMembersMobile2(_ref) {
  var _GroupChatMembersList, _GroupChatMembersList2;
  var allProfilesRef = _ref.allProfilesRef, onClose = _ref.onClose, handleSubmitSuccess = _ref.handleSubmitSuccess, profileId = _ref.profileId, roomId = _ref.roomId, isPending = _ref.isPending, _ref$GroupChatMembers = _ref.GroupChatMembersList, GroupChatMembersList = _ref$GroupChatMembers === void 0 ? GroupChatMembersList_default : _ref$GroupChatMembers, _ref$GroupChatMembers2 = _ref.GroupChatMembersListProps, GroupChatMembersListProps = _ref$GroupChatMembers2 === void 0 ? {} : _ref$GroupChatMembers2, _ref$existingMembers = _ref.existingMembers, existingMembers = _ref$existingMembers === void 0 ? [] : _ref$existingMembers;
  var _useNotification = useNotification(), sendToast = _useNotification.sendToast;
  var _useAllProfilesList = useAllProfilesList(allProfilesRef), allProfiles = _useAllProfilesList.data.allProfiles, loadNext = _useAllProfilesList.loadNext, isLoadingNext = _useAllProfilesList.isLoadingNext, hasNext = _useAllProfilesList.hasNext, refetchProfiles = _useAllProfilesList.refetch;
  var formReturn = useForm({
    defaultValues: DEFAULT_CREATE_OR_EDIT_GROUP_FORM_VALUE,
    // @ts-ignore TODO: check typing issue with zodResolver
    resolver: zodResolver(DEFAULT_FORM_VALIDATION),
    mode: "onBlur"
  });
  var setValue = formReturn.setValue, watch = formReturn.watch, getFieldState = formReturn.getFieldState, handleSubmit = formReturn.handleSubmit, isDirty = formReturn.formState.isDirty, reset = formReturn.reset;
  var _useUpdateChatRoomMut = useUpdateChatRoomMutation(), _useUpdateChatRoomMut2 = _slicedToArray(_useUpdateChatRoomMut, 2), commit = _useUpdateChatRoomMut2[0], isMutationInFlight = _useUpdateChatRoomMut2[1];
  var onSubmit = handleSubmit(function(data) {
    if (!roomId) return;
    var participants2 = data.participants;
    var participantsIds = (participants2 || []).map(function(member) {
      return member === null || member === void 0 ? void 0 : member.id;
    });
    commit({
      variables: {
        input: {
          roomId,
          profileId,
          addParticipants: participantsIds
        },
        connections: []
      },
      onCompleted: function onCompleted(response) {
        var _response$chatRoomUpd;
        var errors = response === null || response === void 0 || (_response$chatRoomUpd = response.chatRoomUpdate) === null || _response$chatRoomUpd === void 0 ? void 0 : _response$chatRoomUpd.errors;
        if (errors) {
          sendToast("Something went wrong", {
            type: "error"
          });
          setFormRelayErrors(formReturn, errors);
        } else {
          handleSubmitSuccess();
          reset();
        }
      }
    });
  });
  var participants = watch(CREATE_OR_EDIT_GROUP_FORM_VALUE.participants);
  var profiles = useMemo(function() {
    return (allProfiles === null || allProfiles === void 0 ? void 0 : allProfiles.edges.filter(function(edge) {
      return (edge === null || edge === void 0 ? void 0 : edge.node) && (edge === null || edge === void 0 ? void 0 : edge.node.id) !== profileId;
    }).map(function(edge) {
      return edge === null || edge === void 0 ? void 0 : edge.node;
    })) || [];
  }, [allProfiles, profileId]);
  var isEditButtonDisabled = !isDirty || getFieldState(CREATE_OR_EDIT_GROUP_FORM_VALUE.participants).invalid;
  var handleAddMember = function handleAddMember2(profile) {
    setValue(CREATE_OR_EDIT_GROUP_FORM_VALUE.participants, [].concat(_toConsumableArray(participants), [profile]), {
      shouldValidate: true,
      shouldDirty: true,
      shouldTouch: true
    });
  };
  var handleRemoveMember = function handleRemoveMember2(profile) {
    setValue(CREATE_OR_EDIT_GROUP_FORM_VALUE.participants, participants.filter(function(member) {
      return (member === null || member === void 0 ? void 0 : member.id) !== (profile === null || profile === void 0 ? void 0 : profile.id);
    }), {
      shouldValidate: true,
      shouldDirty: true,
      shouldTouch: true
    });
  };
  var emptyParticipantsList = participants.length === 0;
  return /* @__PURE__ */ _jsxs(Box, {
    children: [/* @__PURE__ */ _jsxs(Container, {
      children: [/* @__PURE__ */ _jsx(IconButton, {
        onClick: onClose,
        "aria-label": "cancel adding member",
        children: /* @__PURE__ */ _jsx(Iconify, {
          icon: "eva:arrow-ios-back-fill",
          width: 24
        })
      }), /* @__PURE__ */ _jsx(Typography, {
        component: "span",
        variant: "subtitle2",
        sx: {
          textAlign: "center"
        },
        children: "Add Member"
      }), /* @__PURE__ */ _jsx(IconButton, {
        "aria-label": "Add Member",
        disabled: isEditButtonDisabled || isPending,
        isLoading: isMutationInFlight || isPending,
        onClick: function onClick() {
          onSubmit();
        },
        children: /* @__PURE__ */ _jsx(CheckMarkIcon, {
          sx: {
            fontSize: "24px"
          }
        })
      })]
    }), /* @__PURE__ */ _jsx(GroupChatMembersList, _objectSpread({
      FORM_VALUE: CREATE_OR_EDIT_GROUP_FORM_VALUE,
      setValue,
      watch,
      currentParticipants: participants,
      connections: profiles,
      refetch: refetchProfiles,
      SearchbarContainer,
      connectionsLoadNext: loadNext,
      connectionsHasNext: hasNext,
      connectionsIsLoadingNext: isLoadingNext,
      ConnectionsListProps: _objectSpread({
        VirtuosoProps: {
          style: {
            height: "100%",
            maxHeight: emptyParticipantsList ? "calc(100vh - 72px - 57px - 69px)" : "calc(100vh - 72px - 57px - 69px - 130px)"
          }
        },
        title: "",
        removeTitle: emptyParticipantsList,
        renderItem: function renderItem(profile) {
          if (!profile) return null;
          return /* @__PURE__ */ _jsx(AddMemberCard_default, {
            profile,
            handleAddMember,
            handleRemoveMember,
            isBeingAdded: participants.some(function(member) {
              return (member === null || member === void 0 ? void 0 : member.id) === (profile === null || profile === void 0 ? void 0 : profile.id);
            }),
            isExistingMember: existingMembers.some(function(member) {
              return (member === null || member === void 0 ? void 0 : member.id) === (profile === null || profile === void 0 ? void 0 : profile.id);
            })
          });
        }
      }, (_GroupChatMembersList = GroupChatMembersListProps === null || GroupChatMembersListProps === void 0 ? void 0 : GroupChatMembersListProps.ConnectionsListProps) !== null && _GroupChatMembersList !== void 0 ? _GroupChatMembersList : {}),
      MembersListProps: _objectSpread({
        removeTitle: emptyParticipantsList,
        title: "",
        NormalListProps: {
          sx: {
            display: "flex",
            justifyContent: "start",
            alignItems: "center",
            padding: emptyParticipantsList ? 0 : "12px",
            scrollbarWidth: "none"
          }
        }
      }, (_GroupChatMembersList2 = GroupChatMembersListProps === null || GroupChatMembersListProps === void 0 ? void 0 : GroupChatMembersListProps.MembersListProps) !== null && _GroupChatMembersList2 !== void 0 ? _GroupChatMembersList2 : {}),
      ProfileCard: AddedMemberCard_default
    }, GroupChatMembersListProps))]
  });
};
var AddMembersMobile_default = AddMembersMobile;

export {
  AddMembersMobile_default
};
//# sourceMappingURL=chunk-S4A6TPVD.mjs.map