"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _react = require("react");
var _reactNative = require("react-native");
var _reactNativeSvg = require("react-native-svg");
var _user = require("../../../../core/legacy/user");
var _xml = require("../../../../core/assets/icons/xml");
var _native = require("@react-navigation/native");
var _useAuth = _interopRequireDefault(require("../../../../core/hooks/useAuth"));
var _styles = require("./styles");
var _reactNativePaper = require("react-native-paper");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const CreatePostChooseTargetModal = ({
  visible,
  onClose,
  userId,
  onSelect,
  postType
}) => {
  const theme = (0, _reactNativePaper.useTheme)();
  const styles = (0, _styles.useStyles)();
  const {
    apiRegion
  } = (0, _useAuth.default)();
  const [communities, setCommunities] = (0, _react.useState)([]);
  const [hasNextPageFunc, setHasNextPageFunc] = (0, _react.useState)(false);
  const [myUser, setMyUser] = (0, _react.useState)();
  const onNextPageRef = (0, _react.useRef)(null);
  const isFetchingRef = (0, _react.useRef)(false);
  const onEndReachedCalledDuringMomentumRef = (0, _react.useRef)(true);
  const navigation = (0, _native.useNavigation)();
  const getMyUserDetail = (0, _react.useCallback)(async () => {
    if (userId) {
      const {
        userObject
      } = await (0, _user.getAmityUser)(userId);
      let formattedUserObject;
      formattedUserObject = {
        userId: userObject.data.userId,
        displayName: userObject.data.displayName,
        avatarFileId: userObject.data.avatarFileId
      };
      setMyUser(formattedUserObject);
    }
  }, [userId]);
  (0, _react.useEffect)(() => {
    if (userId) {
      getMyUserDetail();
    }
  }, [getMyUserDetail, userId]);
  (0, _react.useEffect)(() => {
    const loadCommunities = async () => {
      try {
        const unsubscribe = _tsSdkReactNative.CommunityRepository.getCommunities({
          membership: 'member',
          limit: 10
        }, ({
          data: communitiesList,
          onNextPage,
          hasNextPage,
          loading
        }) => {
          if (!loading) {
            setCommunities(prevCommunities => [...prevCommunities, ...communitiesList]);
            setHasNextPageFunc(hasNextPage);
            onNextPageRef.current = onNextPage;
            isFetchingRef.current = false;
            unsubscribe();
          }
        });
      } catch (error) {
        console.error('Failed to load communities:', error);
        isFetchingRef.current = false;
      }
    };
    loadCommunities();
  }, []);
  const renderMyTimeLine = () => {
    return /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
      onPress: () => onSelectFeed(userId, 'My Timeline', 'user'),
      style: styles.rowContainerMyTimeLine
    }, /*#__PURE__*/React.createElement(_reactNative.Image, {
      style: styles.avatar,
      source: myUser ? {
        uri: `https://api.${apiRegion}.amity.co/api/v3/files/${myUser.avatarFileId}/download`
      } : require('./../../../../../assets/icon/Placeholder.png')
    }), /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: styles.communityText
    }, "My Timeline"));
  };
  const onSelectFeed = (targetId, targetName, targetType, isPublic, postSetting, needApprovalOnPostCreation) => {
    onSelect && onSelect();
    const targetscreen = () => {
      if (postType === 'post') return 'CreatePost';
      if (postType === 'poll') return 'CreatePoll';
      if (postType === 'room') return 'CreateLivestream';
      return null;
    };
    navigation.navigate(targetscreen(), {
      targetId: targetId,
      targetName: targetName,
      targetType: targetType,
      postSetting: postSetting,
      isPublic: isPublic,
      needApprovalOnPostCreation: needApprovalOnPostCreation
    });
  };
  const renderCommunity = ({
    item
  }) => {
    return /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
      key: item.communityId,
      onPress: () => onSelectFeed(item.communityId, item.displayName, 'community', item.isPublic, item.postSetting, item.needApprovalOnPostCreation),
      style: styles.rowContainer
    }, /*#__PURE__*/React.createElement(_reactNative.Image, {
      style: styles.avatar,
      source: item.avatarFileId ? {
        uri: `https://api.${apiRegion}.amity.co/api/v3/files/${item.avatarFileId}/download`
      } : require('./../../../../../assets/icon/Placeholder.png')
    }), /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: styles.communityText
    }, item.displayName));
  };
  const handleEndReached = () => {
    if (!isFetchingRef.current && hasNextPageFunc && !onEndReachedCalledDuringMomentumRef.current) {
      isFetchingRef.current = true;
      onEndReachedCalledDuringMomentumRef.current = true;
      onNextPageRef.current && onNextPageRef.current();
    }
  };
  return /*#__PURE__*/React.createElement(_reactNative.Modal, {
    visible: visible,
    animationType: "slide",
    onTouchEnd: handleEndReached
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.container
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.header
  }, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.closeButton,
    onPress: onClose
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.closeIcon)(theme.colors.base),
    width: "17",
    height: "17"
  })), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.headerTextContainer
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.headerText
  }, "Post To"))), renderMyTimeLine(), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.myCommunityText
  }, "My Community"), /*#__PURE__*/React.createElement(_reactNative.ScrollView, {
    onScroll: ({
      nativeEvent
    }) => {
      const yOffset = nativeEvent.contentOffset.y;
      const contentHeight = nativeEvent.contentSize.height;
      const scrollViewHeight = nativeEvent.layoutMeasurement.height;
      const isNearBottom = contentHeight - yOffset <= scrollViewHeight * 1.7; // Adjust the multiplier as needed

      if (isNearBottom) {
        handleEndReached();
      }
    },
    scrollEventThrottle: 16 // Adjust as needed
  }, communities.map(item => renderCommunity({
    item
  })))));
};
var _default = exports.default = /*#__PURE__*/(0, _react.memo)(CreatePostChooseTargetModal);
//# sourceMappingURL=CreatePostChooseTargetModal.js.map