import React, {memo, useCallback, useEffect, useMemo, useRef} from 'react';
import {FlatList, FlatListProps, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {shallowEqual, useDispatch} from 'react-redux';
import {useNavigation} from '@react-navigation/native';
import {AbsolutePill, ListEmpty, PostSkeleton} from '@components';
import {Navigation} from '@interfaces/navigation';
import {PostsData} from '@modules/post/interfaces';
import {setHasNewPosts, setScrollToTop} from '@modules/post/store';
import CreatePostButton from '@modules/post/components/CreatePostButton';
import FeedPostItem from '@modules/post/components/FeedPostItem';
import {useVisiblePostsHandlers} from '@modules/post/hooks/useVisiblePosts';
import {onViewPost} from '@modules/post/utils';
import {useAppSelector} from '@redux/utils';
import {DEFAULT_THRESHOLD, Screens} from '@shared/constants';
import {scrollToTopFlatList} from '@shared/utils';
import {useTheme} from '@shared/theme';
import {useVisiblePosts} from '@shared/stores/useActivePostsStore';

import Alerts from '../Alerts';
import {styles} from './styles';
import PinnedPosts from '../PinnedPosts';

interface Props {
  hasNextPage?: boolean;
  postIds?: number[];
  pinnedPostIds?: number[];
  onEndReached?: FlatListProps<PostsData>['onEndReached'];
  refreshControl?: FlatListProps<PostsData>['refreshControl'];
}

function FeedPosts({
  hasNextPage = false,
  onEndReached,
  postIds = [],
  pinnedPostIds = [],
  refreshControl,
}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {
    instanceId,
    userId,
    scrollToTop,
    showPublishButton,
    canManageComments,
    canManagePosts,
    hasNewPosts,
  } = useAppSelector(
    ({instance, user, posts: storedPosts}) => ({
      instanceId: instance.id,
      userId: user.id,
      scrollToTop: storedPosts.scrollToTop,
      hasNewPosts: storedPosts.hasNewPosts,
      showPublishButton:
        user.permissions.CREATE_POSTS && !storedPosts.postCreationInProgress,
      canManagePosts: user.permissions.MANAGE_POSTS,
      canManageComments:
        user.permissions.MANAGE_COMMENTS ||
        user.permissions.MANAGE_FEED_COMMENTS,
    }),
    shallowEqual,
  );
  const {setScreenActiveKey} = useVisiblePosts();

  useEffect(() => {
    setScreenActiveKey('feed');
  }, [setScreenActiveKey]);

  const {viewabilityConfigCallbackPairs} = useVisiblePostsHandlers({
    screenKey: 'feed',
    onViewPost: onViewPost({userId, instanceId}),
    defaultVisiblePostIds: pinnedPostIds,
  });
  const dispatch = useDispatch();
  const navigation = useNavigation<Navigation['navigation']>();
  const flatListRef = useRef<Nullable<FlatList<number>>>(null);

  const onPillAction = useCallback(
    () => dispatch(setHasNewPosts(false)),
    [dispatch],
  );

  const checkNewPosts = useCallback(() => {
    onPillAction();
    scrollToTopFlatList(flatListRef);
  }, [onPillAction]);

  const keyExtractor = useCallback((item: number) => `${item}`, []);

  const renderPostItem = useCallback(
    ({item}: {item: number}) => (
      <FeedPostItem
        screenKey="feed"
        postId={item}
        canManagePosts={canManagePosts}
        canManageComments={canManageComments}
      />
    ),
    [canManageComments, canManagePosts],
  );

  useEffect(() => {
    if (scrollToTop) {
      scrollToTopFlatList(flatListRef);
      dispatch(setScrollToTop(false));
    }
  }, [dispatch, scrollToTop]);

  const onPressCreatePost = () => {
    navigation.navigate(Screens.PUBLISH_POST);
  };

  const ListHeaderComponent = (
    <View style={styles.gap}>
      {showPublishButton && (
        <CreatePostButton
          onPress={onPressCreatePost}
          style={styles.createPostButton}
        />
      )}
      <Alerts />
      {!!pinnedPostIds.length && <PinnedPosts pinnedPostIds={pinnedPostIds} />}
    </View>
  );

  const data = useMemo(
    () =>
      postIds.filter(
        post => !pinnedPostIds?.some(pinnedPost => pinnedPost === post),
      ),
    [pinnedPostIds, postIds],
  );

  return (
    <View style={[styles.safeAreaView]}>
      {hasNewPosts && (
        <AbsolutePill
          text={t('post.new_publications')}
          onPress={checkNewPosts}
        />
      )}
      <FlatList
        ref={flatListRef}
        data={data}
        showsVerticalScrollIndicator={false}
        removeClippedSubviews={false}
        keyExtractor={keyExtractor}
        renderItem={renderPostItem}
        onStartReached={onPillAction}
        onEndReached={onEndReached}
        onEndReachedThreshold={DEFAULT_THRESHOLD}
        maintainVisibleContentPosition={{minIndexForVisible: 1}}
        refreshControl={refreshControl}
        contentContainerStyle={[
          styles.contentContainer,
          {backgroundColor: theme.background.layout.default},
        ]}
        viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current}
        ListHeaderComponent={ListHeaderComponent}
        ListFooterComponent={
          hasNextPage ? (
            <View style={{backgroundColor: theme.background.layout.default}}>
              <PostSkeleton />
            </View>
          ) : undefined
        }
        ListEmptyComponent={<ListEmpty title={t('post.no_results')} />}
      />
    </View>
  );
}
export default memo(FeedPosts);
