import React, {ReactElement, memo, useCallback, useRef, useState} from 'react';
import {FlatList, FlatListProps, RefreshControlProps, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconInfoCircle} from '@tabler/icons-react-native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {Avatar, ListEmpty, ListFooter, PostSkeleton} from '@components';
import {AbsolutePill} from '@components/_custom/AbsolutePill';
import {styles} from '@components/Posts/styles';
import {ScrollEvent} from '@interfaces/generic';
import GroupPost from '@modules/group/components/GroupPost';
import {onViewPost} from '@modules/group/utils';
import {Post as TPost, PostsData} from '@modules/post/interfaces';
import {useVisiblePostsHandlers} from '@modules/post/hooks/useVisiblePosts';
import {useAppSelector} from '@redux/utils';
import {DEFAULT_THRESHOLD} from '@shared/constants';
import {isCloseToTop, scrollToTopFlatList} from '@shared/utils';
import {useTheme} from '@shared/theme';

interface Props {
  pinnedPost?: TPost;
  postIds?: number[];
  canInteract?: boolean;
  canManagePosts?: boolean;
  refreshControl?: ReactElement<RefreshControlProps>;
  header?: ReactElement;
  onScroll?: (event: ScrollEvent) => void;
  onEndReached?: FlatListProps<PostsData>['onEndReached'];
  ListEmptyComponent?: FlatListProps<PostsData>['ListEmptyComponent'];
  EmptyComponent?: ReactElement;
  groupId: number;
  loadingMore?: boolean;
  canManageComments?: boolean;
  isMarketplace?: boolean;
  pillCondition?: boolean;
  pillAction?: () => void;
  bounces?: boolean;
  isRefreshing?: boolean;
  isArchived?: boolean;
}

const keyExtractor = (item: number) => item.toString();

function Posts({
  canManagePosts,
  refreshControl,
  header,
  onScroll,
  onEndReached,
  groupId,
  loadingMore,
  canInteract = true,
  canManageComments = false,
  pillAction,
  postIds = [],
  pillCondition = false,
  bounces,
  isRefreshing,
  isArchived,
  EmptyComponent,
}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {bottom} = useSafeAreaInsets();
  const instanceId = useAppSelector(({instance}) => instance.id);
  const userId = useAppSelector(({user}) => user.id);
  const flatList = useRef<Nullable<FlatList<number>>>(null);
  const [closeToTop, setCloseToTop] = useState(true);
  const {viewabilityConfigCallbackPairs} = useVisiblePostsHandlers({
    screenKey: 'groups',
    onViewPost: itemId =>
      onViewPost({itemId, userId, instanceId, groupId, canInteract}),
  });

  const checkNewPosts = useCallback(() => {
    pillAction?.();
    scrollToTopFlatList(flatList);
  }, [pillAction]);

  const handleScroll = useCallback(
    (nativeEvent: ScrollEvent) => {
      onScroll?.(nativeEvent);
      setCloseToTop(isCloseToTop(nativeEvent.nativeEvent));
    },
    [onScroll],
  );

  const renderPostItem = useCallback(
    ({item: postId}: {item: number}) => (
      <GroupPost
        postId={postId}
        canManagePosts={canManagePosts}
        canManageComments={canManageComments}
        canInteract={canInteract}
        groupId={groupId}
        isArchived={isArchived}
      />
    ),
    [canManagePosts, canManageComments, canInteract, groupId, isArchived],
  );

  return (
    <View
      style={[
        styles.container,
        {
          backgroundColor: postIds.length
            ? theme.background.layout.default
            : theme.background.elements.default,
        },
      ]}>
      {!groupId && pillCondition && !closeToTop && (
        <AbsolutePill
          text={t('post.new_publications')}
          onPress={checkNewPosts}
        />
      )}
      <FlatList
        ref={flatList}
        data={postIds}
        keyExtractor={keyExtractor}
        renderItem={renderPostItem}
        onScroll={handleScroll}
        onEndReached={onEndReached}
        onEndReachedThreshold={DEFAULT_THRESHOLD}
        refreshControl={refreshControl}
        ListHeaderComponent={header}
        ListEmptyComponent={
          isRefreshing ? (
            <View>
              <PostSkeleton />
              <PostSkeleton />
              <PostSkeleton />
            </View>
          ) : (
            EmptyComponent ?? (
              <ListEmpty
                style={{backgroundColor: theme.background.elements.default}}
                IconComponent={
                  <Avatar Icon={IconInfoCircle} variant="primary" />
                }
                title={t('post.no_results')}
              />
            )
          )
        }
        ListFooterComponent={
          <View
            style={{
              paddingBottom: bottom,
              backgroundColor: theme.background.layout.default,
            }}>
            <ListFooter
              paginationType="infiniteScroll"
              isFetchingNextPage={loadingMore}
              isVisible
            />
          </View>
        }
        viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current}
        contentContainerStyle={styles.contentContainer}
        showsVerticalScrollIndicator={false}
        bounces={bounces}
      />
    </View>
  );
}

export default memo(Posts);
