import { CommunityRepository } from '@amityco/ts-sdk-react-native';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { TouchableOpacity, View, Text, Modal, Image, ScrollView } from 'react-native';
import { SvgXml } from 'react-native-svg';
import { getAmityUser } from '../../../../core/legacy/user';
import { closeIcon } from '../../../../core/assets/icons/xml';
import { useNavigation } from '@react-navigation/native';
import useAuth from '../../../../core/hooks/useAuth';
import { useStyles } from './styles';
import { useTheme } from 'react-native-paper';
const CreatePostChooseTargetModal = ({
  visible,
  onClose,
  userId,
  onSelect,
  postType
}) => {
  const theme = useTheme();
  const styles = useStyles();
  const {
    apiRegion
  } = useAuth();
  const [communities, setCommunities] = useState([]);
  const [hasNextPageFunc, setHasNextPageFunc] = useState(false);
  const [myUser, setMyUser] = useState();
  const onNextPageRef = useRef(null);
  const isFetchingRef = useRef(false);
  const onEndReachedCalledDuringMomentumRef = useRef(true);
  const navigation = useNavigation();
  const getMyUserDetail = useCallback(async () => {
    if (userId) {
      const {
        userObject
      } = await getAmityUser(userId);
      let formattedUserObject;
      formattedUserObject = {
        userId: userObject.data.userId,
        displayName: userObject.data.displayName,
        avatarFileId: userObject.data.avatarFileId
      };
      setMyUser(formattedUserObject);
    }
  }, [userId]);
  useEffect(() => {
    if (userId) {
      getMyUserDetail();
    }
  }, [getMyUserDetail, userId]);
  useEffect(() => {
    const loadCommunities = async () => {
      try {
        const unsubscribe = 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(TouchableOpacity, {
      onPress: () => onSelectFeed(userId, 'My Timeline', 'user'),
      style: styles.rowContainerMyTimeLine
    }, /*#__PURE__*/React.createElement(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(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(TouchableOpacity, {
      key: item.communityId,
      onPress: () => onSelectFeed(item.communityId, item.displayName, 'community', item.isPublic, item.postSetting, item.needApprovalOnPostCreation),
      style: styles.rowContainer
    }, /*#__PURE__*/React.createElement(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(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(Modal, {
    visible: visible,
    animationType: "slide",
    onTouchEnd: handleEndReached
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.container
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.header
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.closeButton,
    onPress: onClose
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: closeIcon(theme.colors.base),
    width: "17",
    height: "17"
  })), /*#__PURE__*/React.createElement(View, {
    style: styles.headerTextContainer
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.headerText
  }, "Post To"))), renderMyTimeLine(), /*#__PURE__*/React.createElement(Text, {
    style: styles.myCommunityText
  }, "My Community"), /*#__PURE__*/React.createElement(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
  })))));
};
export default /*#__PURE__*/memo(CreatePostChooseTargetModal);
//# sourceMappingURL=CreatePostChooseTargetModal.js.map