import React__default, { useState } from 'react';
import ChannelListHeader from './ChannelListHeader.js';
import { AddChannel } from './AddChannel.js';
import ChannelPreview from './ChannelPreview.js';
import ChannelPreviewAction from './ChannelPreviewAction.js';
import { u as useChannelListContext, F as FETCH_CHANNELS_START, a as FETCH_CHANNELS_SUCCESS, b as FETCH_CHANNELS_FAILURE, L as LEAVE_CHANNEL_SUCCESS, S as SET_CURRENT_CHANNEL } from '../../ChannelListProvider-6c1df64a.js';
import useSendbirdStateContext from '../../useSendbirdStateContext.js';
import EditProfile from '../../EditUserProfile.js';
import { P as PlaceHolder, a as PlaceHolderTypes } from '../../index-11fe17e1.js';
import '../../LocalizationContext-1701e5c8.js';
import '../../stringSet-e9bb0333.js';
import '../../index-ff8f2f61.js';
import '../../index-f50d7ab0.js';
import 'prop-types';
import '../../ui/Avatar.js';
import '../../ui/ImageRenderer.js';
import '../../ui/Icon.js';
import '../../uuid-8b344dd2.js';
import '../../ui/IconButton.js';
import '../../_rollupPluginBabelHelpers-cc035350.js';
import '../../CreateChannel.js';
import '../../CreateChannel/components/CreateChannelUI.js';
import '../../CreateChannelProvider-ec477081.js';
import '../../sendbirdSelectors.js';
import '../../topics-0b30f52b.js';
import '../../utils-05aa9060.js';
import '../../CreateChannel/components/InviteUsers.js';
import '../../ui/Modal.js';
import 'react-dom';
import '../../index-44c86e58.js';
import '../../ui/Button.js';
import '../../MediaQueryContext-e5b401d0.js';
import '../../ui/UserListItem.js';
import '../../UserProfileContext-74e9a128.js';
import '../../ui/MutedAvatarOverlay.js';
import '../../ui/Checkbox.js';
import '../../ui/UserProfile.js';
import '../../ui/ContextMenu.js';
import '../../ui/SortByRow.js';
import '../../index-99ab01f6.js';
import '../../utils/message/getOutgoingMessageState.js';
import '../../CreateChannel/components/SelectChannelType.js';
import '../../ui/ChannelAvatar.js';
import '../../utils-cd7ab927.js';
import '../../ui/Badge.js';
import '../../index-0aa8cbad.js';
import '../../index-5a62f6b7.js';
import '../../ui/Loader.js';
import '../../index-7e5538e6.js';
import '../../index-3f8e1a51.js';
import '../../ui/MentionUserLabel.js';
import '../../consts-a0834b70.js';
import '../../ui/TextButton.js';
import '../../color-ea3bf5b8.js';
import '../../Channel/components/TypingIndicator.js';
import '@sendbird/chat/groupChannel';
import '../../ChannelProvider-1dc36682.js';
import '../../const-7c266a95.js';
import '../../compareIds-367bb030.js';
import '@sendbird/chat/message';
import '../../consts-44eaef6b.js';
import '../../resolvedReplyType-6bb8f548.js';
import '../../useLongPress-6d0b6619.js';
import '../../withSendbird.js';
import '../../index-9c80246a.js';
import '../../ui/Input.js';
import '../../actionTypes-cccf62ac.js';

const isAboutSame = (a, b, px) => Math.abs(a - b) <= px;

const DELIVERY_RECIPT = 'delivery_receipt';
const ChannelListUI = props => {
  var _state$stores;
  const {
    renderHeader,
    renderChannelPreview,
    renderPlaceHolderError,
    renderPlaceHolderLoading,
    renderPlaceHolderEmptyList
  } = props;
  const [showProfileEdit, setShowProfileEdit] = useState(false);
  const {
    onThemeChange,
    allowProfileEdit,
    allChannels,
    loading,
    currentChannel,
    channelListDispatcher,
    channelSource,
    typingChannels,
    initialized
  } = useChannelListContext();
  const state = useSendbirdStateContext();
  const sdkStore = state === null || state === void 0 ? void 0 : (_state$stores = state.stores) === null || _state$stores === void 0 ? void 0 : _state$stores.sdkStore;
  const config = state === null || state === void 0 ? void 0 : state.config;
  const {
    logger,
    isOnline = false,
    markAsDeliveredScheduler,
    disableMarkAsDelivered
  } = config;
  const sdk = sdkStore === null || sdkStore === void 0 ? void 0 : sdkStore.sdk;
  const sdkError = sdkStore === null || sdkStore === void 0 ? void 0 : sdkStore.error;
  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("div", {
    className: "sendbird-channel-list__header"
  }, (renderHeader === null || renderHeader === void 0 ? void 0 : renderHeader()) || /*#__PURE__*/React__default.createElement(ChannelListHeader, {
    onEdit: () => {
      if (allowProfileEdit) {
        setShowProfileEdit(true);
      }
    },
    allowProfileEdit: allowProfileEdit,
    renderIconButton: () => /*#__PURE__*/React__default.createElement(AddChannel, null)
  })), showProfileEdit && /*#__PURE__*/React__default.createElement(EditProfile, {
    onThemeChange: onThemeChange,
    onCancel: () => {
      setShowProfileEdit(false);
    },
    onEditProfile: () => {
      setShowProfileEdit(false);
    }
  }), /*#__PURE__*/React__default.createElement("div", {
    className: "sendbird-channel-list__body",
    onScroll: e => {
      const target = e === null || e === void 0 ? void 0 : e.target;
      const fetchMore = isAboutSame(target.clientHeight + target.scrollTop, target.scrollHeight, 10);
      if (fetchMore && channelSource !== null && channelSource !== void 0 && channelSource.hasNext) {
        logger.info('ChannelList: Fetching more channels');
        channelListDispatcher({
          type: FETCH_CHANNELS_START,
          payload: null
        });
        channelSource.next().then(channelList => {
          var _sdk$appInfo, _sdk$appInfo$premiumF;
          logger.info('ChannelList: Fetching channels successful', channelList);
          channelListDispatcher({
            type: FETCH_CHANNELS_SUCCESS,
            payload: channelList
          });
          const canSetMarkAsDelivered = sdk === null || sdk === void 0 ? void 0 : (_sdk$appInfo = sdk.appInfo) === null || _sdk$appInfo === void 0 ? void 0 : (_sdk$appInfo$premiumF = _sdk$appInfo.premiumFeatureList) === null || _sdk$appInfo$premiumF === void 0 ? void 0 : _sdk$appInfo$premiumF.find(feature => feature === DELIVERY_RECIPT);
          if (canSetMarkAsDelivered && !disableMarkAsDelivered) {
            logger.info('ChannelList: Marking all channels as read');
            // eslint-disable-next-line no-unused-expressions
            channelList === null || channelList === void 0 ? void 0 : channelList.forEach(channel => {
              if ((channel === null || channel === void 0 ? void 0 : channel.unreadMessageCount) > 0) {
                markAsDeliveredScheduler.push(channel);
              }
            });
          }
        }).catch(err => {
          logger.info('ChannelList: Fetching channels failed', err);
          channelListDispatcher({
            type: FETCH_CHANNELS_FAILURE,
            payload: err
          });
        });
      }
    }
  }, sdkError && !loading && (renderPlaceHolderError && typeof renderPlaceHolderError === 'function' ? renderPlaceHolderError === null || renderPlaceHolderError === void 0 ? void 0 : renderPlaceHolderError() : /*#__PURE__*/React__default.createElement(PlaceHolder, {
    type: PlaceHolderTypes.WRONG
  })), /*#__PURE__*/React__default.createElement("div", null, allChannels && allChannels.map((channel, idx) => {
    // todo: Refactor and move this inside channel - preview
    const onLeaveChannel = (c, cb) => {
      logger.info('ChannelList: Leaving channel', c);
      c.leave().then(res => {
        logger.info('ChannelList: Leaving channel success', res);
        if (cb && typeof cb === 'function') {
          cb(res, null);
        }
        channelListDispatcher({
          type: LEAVE_CHANNEL_SUCCESS,
          payload: channel === null || channel === void 0 ? void 0 : channel.url
        });
      }).catch(err => {
        logger.error('ChannelList: Leaving channel failed', err);
        if (cb && typeof cb === 'function') {
          cb(null, err);
        }
      });
    };
    const onClick = () => {
      if (!isOnline) {
        return;
      }
      logger.info('ChannelList: Clicked on channel:', channel);
      channelListDispatcher({
        type: SET_CURRENT_CHANNEL,
        payload: channel
      });
    };
    return renderChannelPreview ?
    /*#__PURE__*/
    // eslint-disable-next-line
    React__default.createElement("div", {
      key: channel === null || channel === void 0 ? void 0 : channel.url,
      onClick: onClick
    }, renderChannelPreview({
      channel,
      onLeaveChannel
    })) : /*#__PURE__*/React__default.createElement(ChannelPreview, {
      key: channel === null || channel === void 0 ? void 0 : channel.url,
      tabIndex: idx,
      onClick: onClick,
      channel: channel,
      onLeaveChannel: () => onLeaveChannel(channel, null),
      isActive: (channel === null || channel === void 0 ? void 0 : channel.url) === (currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url),
      isTyping: typingChannels === null || typingChannels === void 0 ? void 0 : typingChannels.some(_ref => {
        let {
          url
        } = _ref;
        return url === (channel === null || channel === void 0 ? void 0 : channel.url);
      }),
      renderChannelAction: () => /*#__PURE__*/React__default.createElement(ChannelPreviewAction, {
        channel: channel,
        disabled: !isOnline,
        onLeaveChannel: () => onLeaveChannel(channel, null)
      })
    });
  })), !initialized && loading && (renderPlaceHolderLoading && typeof renderPlaceHolderLoading === 'function' ? renderPlaceHolderLoading === null || renderPlaceHolderLoading === void 0 ? void 0 : renderPlaceHolderLoading() : /*#__PURE__*/React__default.createElement(PlaceHolder, {
    type: PlaceHolderTypes.LOADING
  })), initialized && (allChannels === null || allChannels === void 0 ? void 0 : allChannels.length) === 0 && (renderPlaceHolderEmptyList && typeof renderPlaceHolderEmptyList === 'function' ? renderPlaceHolderEmptyList === null || renderPlaceHolderEmptyList === void 0 ? void 0 : renderPlaceHolderEmptyList() : /*#__PURE__*/React__default.createElement(PlaceHolder, {
    type: PlaceHolderTypes.NO_CHANNELS
  }))));
};

export { ChannelListUI as default };
//# sourceMappingURL=ChannelListUI.js.map
