import React__default, { useState, useContext, useEffect, useCallback } from 'react';
import Button, { ButtonTypes, ButtonSizes } from './ui/Button.js';
import IconButton from './ui/IconButton.js';
import Icon, { IconTypes, IconColors } from './ui/Icon.js';
import ContextMenu, { MenuItems, MenuItem } from './ui/ContextMenu.js';
import UserListItem$1 from './ChannelSettings/components/UserListItem.js';
import { _ as _objectSpread2 } from './_rollupPluginBabelHelpers-a69fd1ce.js';
import Modal from './ui/Modal.js';
import UserListItem from './ui/UserListItem.js';
import { n as noop } from './utils-4bf6e4e6.js';
import { useChannelSettingsContext } from './ChannelSettings/context.js';
import useSendbirdStateContext from './useSendbirdStateContext.js';
import { a as LocalizationContext, u as useLocalization } from './LocalizationContext-426f3d58.js';
import { u as uuidv4 } from './uuid-2e8efc75.js';

function MembersModal(_ref) {
  var _state$config;
  let {
    onCancel
  } = _ref;
  const [members, setMembers] = useState([]);
  const [memberQuery, setMemberQuery] = useState(null);
  const {
    channel
  } = useChannelSettingsContext();
  const state = useSendbirdStateContext();
  const currentUser = state === null || state === void 0 ? void 0 : (_state$config = state.config) === null || _state$config === void 0 ? void 0 : _state$config.userId;
  const {
    stringSet
  } = useContext(LocalizationContext);
  useEffect(() => {
    const memberListQuery = channel === null || channel === void 0 ? void 0 : channel.createMemberListQuery({
      limit: 20
    });
    memberListQuery.next().then(members => {
      setMembers(members);
    });
    setMemberQuery(memberListQuery);
  }, []);
  return /*#__PURE__*/React__default.createElement("div", null, /*#__PURE__*/React__default.createElement(Modal, {
    isFullScreenOnMobile: true,
    hideFooter: true,
    onCancel: () => onCancel(),
    onSubmit: noop,
    titleText: stringSet.CHANNEL_SETTING__MEMBERS__SEE_ALL_MEMBERS
  }, /*#__PURE__*/React__default.createElement("div", {
    className: "sendbird-more-members__popup-scroll",
    onScroll: e => {
      const {
        hasNext
      } = memberQuery;
      const target = e.target;
      const fetchMore = target.clientHeight + target.scrollTop === target.scrollHeight;
      if (hasNext && fetchMore) {
        memberQuery.next().then(o => {
          setMembers([...members, ...o]);
        });
      }
    }
  }, members.map(member => /*#__PURE__*/React__default.createElement(UserListItem, {
    user: member,
    key: member.userId,
    currentUser: currentUser,
    action: _ref2 => {
      let {
        parentRef,
        actionRef
      } = _ref2;
      return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, (channel === null || channel === void 0 ? void 0 : channel.myRole) === 'operator' && /*#__PURE__*/React__default.createElement(ContextMenu, {
        menuTrigger: toggleDropdown => /*#__PURE__*/React__default.createElement(IconButton, {
          className: "sendbird-user-message__more__menu",
          width: "32px",
          height: "32px",
          onClick: () => {
            toggleDropdown();
          }
        }, /*#__PURE__*/React__default.createElement(Icon, {
          width: "24px",
          height: "24px",
          type: IconTypes.MORE,
          fillColor: IconColors.CONTENT_INVERSE
        })),
        menuItems: closeDropdown => /*#__PURE__*/React__default.createElement(MenuItems, {
          parentContainRef: parentRef,
          parentRef: actionRef // for catching location(x, y) of MenuItems
          ,
          closeDropdown: closeDropdown,
          openLeft: true
        }, /*#__PURE__*/React__default.createElement(MenuItem, {
          disable: currentUser === member.userId,
          onClick: () => {
            if (member.role !== 'operator') {
              channel === null || channel === void 0 ? void 0 : channel.addOperators([member.userId]).then(() => {
                setMembers(members.map(m => {
                  if (m.userId === member.userId) {
                    return _objectSpread2(_objectSpread2({}, member), {}, {
                      role: 'operator'
                    });
                  }
                  return m;
                }));
                closeDropdown();
              });
            } else {
              channel === null || channel === void 0 ? void 0 : channel.removeOperators([member.userId]).then(() => {
                setMembers(members.map(m => {
                  if (m.userId === member.userId) {
                    return _objectSpread2(_objectSpread2({}, member), {}, {
                      role: ''
                    });
                  }
                  return m;
                }));
                closeDropdown();
              });
            }
          },
          dataSbId: `channel_setting_member_context_menu_${member.role !== 'operator' ? 'register_as_operator' : 'unregister_operator'}`
        }, member.role !== 'operator' ? stringSet.CHANNEL_SETTING__MODERATION__REGISTER_AS_OPERATOR : stringSet.CHANNEL_SETTING__MODERATION__UNREGISTER_OPERATOR),
        // No muted members in broadcast channel
        !(channel !== null && channel !== void 0 && channel.isBroadcast) && /*#__PURE__*/React__default.createElement(MenuItem, {
          onClick: () => {
            if (member.isMuted) {
              channel === null || channel === void 0 ? void 0 : channel.unmuteUser(member).then(() => {
                setMembers(members.map(m => {
                  if (m.userId === member.userId) {
                    return _objectSpread2(_objectSpread2({}, member), {}, {
                      isMuted: false
                    });
                  }
                  return m;
                }));
                closeDropdown();
              });
            } else {
              channel === null || channel === void 0 ? void 0 : channel.muteUser(member).then(() => {
                setMembers(members.map(m => {
                  if (m.userId === member.userId) {
                    return _objectSpread2(_objectSpread2({}, member), {}, {
                      isMuted: true
                    });
                  }
                  return m;
                }));
                closeDropdown();
              });
            }
          },
          dataSbId: `channel_setting_member_context_menu_${member.isMuted ? 'unmute' : 'mute'}`
        }, member.isMuted ? stringSet.CHANNEL_SETTING__MODERATION__UNMUTE : stringSet.CHANNEL_SETTING__MODERATION__MUTE), /*#__PURE__*/React__default.createElement(MenuItem, {
          onClick: () => {
            channel === null || channel === void 0 ? void 0 : channel.banUser(member, -1, '').then(() => {
              setMembers(members.filter(_ref3 => {
                let {
                  userId
                } = _ref3;
                return userId !== member.userId;
              }));
            });
          },
          dataSbId: "channel_setting_member_context_menu_ban"
        }, stringSet.CHANNEL_SETTING__MODERATION__BAN))
      }));
    }
  })))));
}

const isAboutSame = (a, b, px) => Math.abs(a - b) <= px;
function InviteUsers(_ref) {
  var _state$stores, _state$stores$sdkStor, _state$config;
  let {
    onCancel,
    onSubmit
  } = _ref;
  const [members, setMembers] = useState([]);
  const [selectedMembers, setSelectedMembers] = useState({});
  const [userQuery, setUserQuery] = useState(null);
  const state = useSendbirdStateContext();
  const sdk = state === null || state === void 0 ? void 0 : (_state$stores = state.stores) === null || _state$stores === void 0 ? void 0 : (_state$stores$sdkStor = _state$stores.sdkStore) === null || _state$stores$sdkStor === void 0 ? void 0 : _state$stores$sdkStor.sdk;
  const globalUserListQuery = state === null || state === void 0 ? void 0 : (_state$config = state.config) === null || _state$config === void 0 ? void 0 : _state$config.userListQuery;
  const {
    channel,
    overrideInviteUser,
    queries
  } = useChannelSettingsContext();
  const userFilledQuery = _objectSpread2({}, queries === null || queries === void 0 ? void 0 : queries.applicationUserListQuery);
  const {
    stringSet
  } = useLocalization();
  useEffect(() => {
    const userListQuery = globalUserListQuery ? globalUserListQuery() : sdk === null || sdk === void 0 ? void 0 : sdk.createApplicationUserListQuery(userFilledQuery);
    if (userListQuery !== null && userListQuery !== void 0 && userListQuery.next) {
      userListQuery.next().then(members => {
        setMembers(members);
      });
      setUserQuery(userListQuery);
    }
  }, [sdk]);
  return /*#__PURE__*/React__default.createElement("div", null, /*#__PURE__*/React__default.createElement(Modal, {
    isFullScreenOnMobile: true,
    disabled: Object.keys(selectedMembers).length === 0,
    submitText: stringSet.BUTTON__INVITE,
    type: ButtonTypes.PRIMARY,
    onCancel: () => onCancel(),
    onSubmit: () => {
      const members = Object.keys(selectedMembers).filter(m => selectedMembers[m]);
      if (typeof overrideInviteUser === 'function') {
        overrideInviteUser({
          users: members,
          onClose: onCancel,
          channel
        });
        return;
      }
      channel === null || channel === void 0 ? void 0 : channel.inviteWithUserIds(members).then(() => {
        onSubmit(members);
      });
    },
    titleText: stringSet.CHANNEL_SETTING__MEMBERS__SELECT_TITLE
  }, /*#__PURE__*/React__default.createElement("div", {
    className: "sendbird-more-members__popup-scroll",
    onScroll: e => {
      const {
        hasNext
      } = userQuery;
      const target = e.target;
      const fetchMore = isAboutSame(target.clientHeight + target.scrollTop, target.scrollHeight, 20);
      if (hasNext && fetchMore) {
        userQuery.next().then(users => {
          setMembers([...members, ...users]);
        });
      }
    }
  }, /*#__PURE__*/React__default.createElement("div", {
    className: "sendbird-more-members__popup-scroll__inner"
  }, members.map(member => {
    var _channel$members;
    const isJoinedMember = channel === null || channel === void 0 ? void 0 : (_channel$members = channel.members) === null || _channel$members === void 0 ? void 0 : _channel$members.some(_ref2 => {
      let {
        userId
      } = _ref2;
      return userId === (member === null || member === void 0 ? void 0 : member.userId);
    });
    return /*#__PURE__*/React__default.createElement(UserListItem, {
      checkBox: true,
      checked: isJoinedMember || selectedMembers[member.userId],
      disabled: isJoinedMember,
      onChange: event => {
        const modifiedSelectedMembers = _objectSpread2(_objectSpread2({}, selectedMembers), {}, {
          [event.target.id]: event.target.checked
        });
        if (!event.target.checked) {
          delete modifiedSelectedMembers[event.target.id];
        }
        setSelectedMembers(modifiedSelectedMembers);
      },
      user: member,
      key: member.userId
    });
  })))));
}

const MemberList = () => {
  var _state$stores, _state$stores$sdkStor, _state$config;
  const [members, setMembers] = useState([]);
  const [hasNext, setHasNext] = useState(false);
  const [showAllMembers, setShowAllMembers] = useState(false);
  const [showInviteUsers, setShowInviteUsers] = useState(false);
  const state = useSendbirdStateContext();
  const {
    channel,
    setChannelUpdateId
  } = useChannelSettingsContext();
  const {
    stringSet
  } = useContext(LocalizationContext);
  const sdk = state === null || state === void 0 ? void 0 : (_state$stores = state.stores) === null || _state$stores === void 0 ? void 0 : (_state$stores$sdkStor = _state$stores.sdkStore) === null || _state$stores$sdkStor === void 0 ? void 0 : _state$stores$sdkStor.sdk;
  const userId = state === null || state === void 0 ? void 0 : (_state$config = state.config) === null || _state$config === void 0 ? void 0 : _state$config.userId;
  useEffect(() => {
    if (!channel) {
      setMembers([]);
      return;
    }
    const memberUserListQuery = channel === null || channel === void 0 ? void 0 : channel.createMemberListQuery({
      limit: 10
    });
    memberUserListQuery.next().then(members => {
      setMembers(members);
      setHasNext(memberUserListQuery.hasNext);
    });
  }, [channel]);
  const refreshList = useCallback(() => {
    if (!channel) {
      setMembers([]);
      return;
    }
    const memberUserListQuery = channel === null || channel === void 0 ? void 0 : channel.createMemberListQuery({
      limit: 10
    });
    memberUserListQuery.next().then(members => {
      setMembers(members);
      setHasNext(memberUserListQuery.hasNext);
      setChannelUpdateId(uuidv4());
    });
  }, [channel]);
  return /*#__PURE__*/React__default.createElement("div", {
    className: "sendbird-channel-settings-member-list sendbird-accordion"
  }, members.map(member => /*#__PURE__*/React__default.createElement(UserListItem$1, {
    key: member.userId,
    user: member,
    currentUser: sdk.currentUser.userId,
    action: (channel === null || channel === void 0 ? void 0 : channel.myRole) === 'operator' && userId !== member.userId ? _ref => {
      let {
        actionRef,
        parentRef
      } = _ref;
      return /*#__PURE__*/React__default.createElement(ContextMenu, {
        menuTrigger: toggleDropdown => /*#__PURE__*/React__default.createElement(IconButton, {
          className: "sendbird-user-message__more__menu",
          width: "32px",
          height: "32px",
          onClick: toggleDropdown
        }, /*#__PURE__*/React__default.createElement(Icon, {
          width: "24px",
          height: "24px",
          type: IconTypes.MORE,
          fillColor: IconColors.CONTENT_INVERSE
        })),
        menuItems: closeDropdown => /*#__PURE__*/React__default.createElement(MenuItems, {
          parentContainRef: parentRef,
          parentRef: actionRef // for catching location(x, y) of MenuItems
          ,
          closeDropdown: closeDropdown,
          openLeft: true
        }, /*#__PURE__*/React__default.createElement(MenuItem, {
          onClick: () => {
            if (member.role !== 'operator') {
              channel === null || channel === void 0 ? void 0 : channel.addOperators([member.userId]).then(() => {
                refreshList();
                closeDropdown();
              });
            } else {
              channel === null || channel === void 0 ? void 0 : channel.removeOperators([member.userId]).then(() => {
                refreshList();
                closeDropdown();
              });
            }
          },
          dataSbId: `channel_setting_member_context_menu_${member.role !== 'operator' ? 'register_as_operator' : 'unregister_operator'}`
        }, member.role !== 'operator' ? stringSet.CHANNEL_SETTING__MODERATION__REGISTER_AS_OPERATOR : stringSet.CHANNEL_SETTING__MODERATION__UNREGISTER_OPERATOR),
        // No muted members in broadcast channel
        !(channel !== null && channel !== void 0 && channel.isBroadcast) && /*#__PURE__*/React__default.createElement(MenuItem, {
          onClick: () => {
            if (member.isMuted) {
              channel === null || channel === void 0 ? void 0 : channel.unmuteUser(member).then(() => {
                refreshList();
                closeDropdown();
              });
            } else {
              channel === null || channel === void 0 ? void 0 : channel.muteUser(member).then(() => {
                refreshList();
                closeDropdown();
              });
            }
          },
          dataSbId: `channel_setting_member_context_menu_${member.isMuted ? 'unmute' : 'mute'}`
        }, member.isMuted ? stringSet.CHANNEL_SETTING__MODERATION__UNMUTE : stringSet.CHANNEL_SETTING__MODERATION__MUTE), /*#__PURE__*/React__default.createElement(MenuItem, {
          onClick: () => {
            channel === null || channel === void 0 ? void 0 : channel.banUser(member, -1, '').then(() => {
              refreshList();
              closeDropdown();
            });
          },
          dataSbId: "channel_setting_member_context_menu_ban"
        }, stringSet.CHANNEL_SETTING__MODERATION__BAN))
      });
    } : null
  })), /*#__PURE__*/React__default.createElement("div", {
    className: "sendbird-channel-settings-accordion__footer"
  }, hasNext && /*#__PURE__*/React__default.createElement(Button, {
    type: ButtonTypes.SECONDARY,
    size: ButtonSizes.SMALL,
    onClick: () => setShowAllMembers(true)
  }, stringSet.CHANNEL_SETTING__MEMBERS__SEE_ALL_MEMBERS), /*#__PURE__*/React__default.createElement(Button, {
    type: ButtonTypes.SECONDARY,
    size: ButtonSizes.SMALL,
    onClick: () => setShowInviteUsers(true)
  }, stringSet.CHANNEL_SETTING__MEMBERS__INVITE_MEMBER)), showAllMembers && /*#__PURE__*/React__default.createElement(MembersModal, {
    onCancel: () => {
      setShowAllMembers(false);
      refreshList();
    }
  }), showInviteUsers && /*#__PURE__*/React__default.createElement(InviteUsers, {
    onSubmit: () => {
      setShowInviteUsers(false);
      refreshList();
    },
    onCancel: () => setShowInviteUsers(false)
  }));
};

export { MemberList as M };
//# sourceMappingURL=MemberList-125753a0.js.map
