import { FlatList, View } from 'react-native';
import { useState, useRef, memo, useEffect, useCallback } from 'react';
import { CommentRepository } from '@amityco/ts-sdk-react-native';
import CommentListItem from './CommentListItem/CommentListItem';
import { deleteCommentById } from '../../../../../core/legacy/comment';
import { ComponentID, PageID } from '../../../../enums';
import { useAmityComponent } from '../../../../hooks';
import ContentLoader, { Circle, Rect } from 'react-content-loader/native';
import { isAmityAd } from '../../../../hooks/useCustomRankingGlobalFeed';
import CommentAdComponent from '../../../../components/CommentAdComponent/CommentAdComponent';
import { usePaginatorApi } from '../../../../hooks/usePaginator';
import { useCommentAdImpression } from '../../../../hooks/useCommentAdImpression';
import { useStyles } from './styles';
const commentListLimit = 10;
const AmityPostCommentComponent = ({
  pageId = PageID.WildCardPage,
  postId,
  communityId,
  postType,
  disabledInteraction,
  setReplyUserName,
  setReplyCommentId,
  ListHeaderComponent
}) => {
  const componentId = ComponentID.CommentTray;
  const {
    isExcluded,
    themeStyles
  } = useAmityComponent({
    pageId,
    componentId
  });
  const styles = useStyles();
  const onNextPageRef = useRef(null);
  const [commentList, setCommentList] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const {
    handleViewChange
  } = useCommentAdImpression();
  const {
    itemWithAds
  } = usePaginatorApi({
    items: commentList,
    isLoading,
    placement: 'comment',
    communityId,
    pageSize: commentListLimit,
    getItemId: item => item.commentId
  });
  useEffect(() => {
    if (!postId) return () => {};
    const unsubComment = CommentRepository.getComments({
      dataTypes: {
        matchType: 'any',
        values: ['text', 'image']
      },
      referenceId: postId,
      referenceType: postType,
      limit: commentListLimit
    }, ({
      loading,
      data,
      hasNextPage,
      onNextPage
    }) => {
      if (!loading) {
        data && data.length > 0 && queryComment(data);
        onNextPageRef.current = hasNextPage ? onNextPage : null;
        setTimeout(() => {
          setIsLoading(false);
        }, 1000);
      }
    });
    return () => {
      setCommentList([]);
      unsubComment();
    };
  }, [postId, postType]);
  const queryComment = comments => {
    const formattedCommentList = comments.map(item => {
      var _item$creator, _item$creator2, _item$creator3, _item$creator4, _item$creator5, _item$metadata;
      const formattedUserObject = {
        userId: (_item$creator = item.creator) === null || _item$creator === void 0 ? void 0 : _item$creator.userId,
        displayName: (_item$creator2 = item.creator) === null || _item$creator2 === void 0 ? void 0 : _item$creator2.displayName,
        avatarFileId: (_item$creator3 = item.creator) === null || _item$creator3 === void 0 ? void 0 : _item$creator3.avatarFileId,
        avatarCustomUrl: (_item$creator4 = item.creator) === null || _item$creator4 === void 0 ? void 0 : _item$creator4.avatarCustomUrl,
        isBrand: (_item$creator5 = item.creator) === null || _item$creator5 === void 0 ? void 0 : _item$creator5.isBrand
      };
      return {
        targetType: item.targetType,
        targetId: item.targetId,
        commentId: item.commentId,
        data: item.data,
        dataType: (item === null || item === void 0 ? void 0 : item.dataType) || 'text',
        myReactions: item.myReactions,
        reactions: item.reactions,
        user: formattedUserObject,
        updatedAt: item.updatedAt,
        editedAt: item.editedAt,
        createdAt: item.createdAt,
        childrenComment: item.children,
        childrenNumber: item.childrenNumber,
        referenceId: item.referenceId,
        mentionPosition: (item === null || item === void 0 || (_item$metadata = item.metadata) === null || _item$metadata === void 0 ? void 0 : _item$metadata.mentioned) ?? []
      };
    });
    setCommentList([...formattedCommentList]);
  };
  const onDeleteComment = useCallback(async commentId => {
    const isDeleted = await deleteCommentById(commentId);
    if (isDeleted) {
      const prevCommentList = [...commentList];
      const updatedCommentList = prevCommentList.filter(item => item.commentId !== commentId);
      setCommentList(updatedCommentList);
    }
  }, [commentList]);
  const handleClickReply = useCallback((user, commentId) => {
    setReplyUserName(user.displayName);
    setReplyCommentId(commentId);
  }, [setReplyCommentId, setReplyUserName]);
  const renderCommentListItem = useCallback(({
    item
  }) => {
    if (isLoading) {
      return /*#__PURE__*/React.createElement(ContentLoader, {
        height: 100,
        speed: 1,
        width: 300,
        backgroundColor: themeStyles.colors.baseShade4,
        foregroundColor: themeStyles.colors.baseShade2,
        viewBox: "0 0 300 70"
      }, /*#__PURE__*/React.createElement(Circle, {
        cx: "24",
        cy: "24",
        r: "12"
      }), /*#__PURE__*/React.createElement(Rect, {
        x: "50",
        y: "12",
        rx: "5",
        ry: "5",
        width: 220,
        height: 50
      }), /*#__PURE__*/React.createElement(Rect, {
        x: "50",
        y: "74",
        rx: "5",
        ry: "5",
        width: 150,
        height: 8
      }));
    }
    if (isAmityAd(item)) {
      return /*#__PURE__*/React.createElement(CommentAdComponent, {
        ad: item,
        pageId: pageId
      });
    }
    return /*#__PURE__*/React.createElement(CommentListItem, {
      onDelete: onDeleteComment,
      commentDetail: item,
      onClickReply: handleClickReply,
      postType: postType,
      disabledInteraction: disabledInteraction
    });
  }, [disabledInteraction, handleClickReply, isLoading, onDeleteComment, postType, themeStyles.colors.baseShade2, themeStyles.colors.baseShade4, pageId]);
  if (isExcluded) return null;
  return /*#__PURE__*/React.createElement(View, {
    style: styles.commentListContainer
  }, /*#__PURE__*/React.createElement(FlatList, {
    ListHeaderComponent: ListHeaderComponent,
    keyboardShouldPersistTaps: "handled",
    data: itemWithAds,
    renderItem: renderCommentListItem,
    keyExtractor: (item, index) => (isAmityAd(item) ? item.adId : item.commentId) + `_${index}`,
    onEndReachedThreshold: 0.8,
    viewabilityConfig: {
      viewAreaCoveragePercentThreshold: 60
    },
    onEndReached: () => {
      onNextPageRef.current && onNextPageRef.current();
    },
    onViewableItemsChanged: handleViewChange
  }));
};
export default /*#__PURE__*/memo(AmityPostCommentComponent);
//# sourceMappingURL=PostComment.js.map