import React, {useCallback, useEffect, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useDispatch} from 'react-redux';
import {useNavigation, useRoute} from '@react-navigation/native';
import {Spinner, RefreshControl} from '@components';
import {queryClient} from '@config/queryClient';
import {useScreenEffect} from '@hooks/useScreenEffect';
import {useGroupsListeners} from '@modules/group/screens/Groups/hooks/useGroupsListeners';
import {openCelebrationsPopup} from '@modules/celebrations/utils';
import {invalidateUnreads} from '@modules/keyUpdates/utils';
import {postQueryKeys} from '@modules/post/constants';
import {
  useFeedPosts,
  useFeedLoadingStates,
  useFeedActions,
} from '@modules/post/store/useFeedStore';
import {keyUpdatesQueryKeys} from '@modules/keyUpdates/constants';
import {showSnackbar} from '@redux/dispatchers';
import {useCommunityFeature} from '@stores/communityFeatures';

import FeedPosts from './components/FeedPosts';
import {styles} from './styles';

function Feed() {
  const {t} = useTranslation();
  const dispatch = useDispatch();
  const navigation = useNavigation();
  const route = useRoute();
  const canViewGroupPostsInFeed = useCommunityFeature(
    'VIEW_GROUP_POSTS_IN_FEED',
  );

  const {postIds, pinnedPostIds} = useFeedPosts();
  const {hasNextPage, isLoading, isRefetching} = useFeedLoadingStates();
  const {refetch, getNextPage} = useFeedActions();

  const [showTimingToast, setShowTimingToast] = useState(false);

  useGroupsListeners(canViewGroupPostsInFeed);

  // Function shouldn't return Promise for useScreenEffect
  const onRefreshPosts = useCallback(() => {
    (async () => {
      await refetch({includeGroupPosts: canViewGroupPostsInFeed});
      queryClient.invalidateQueries(postQueryKeys.scheduledPosts);
      queryClient.invalidateQueries(keyUpdatesQueryKeys.keyUpdatesPreview);
      queryClient.invalidateQueries(postQueryKeys.feedPendingApprovalPosts());
      setTimeout(() => setShowTimingToast(true), 15000);
      invalidateUnreads();
    })();
  }, [refetch, canViewGroupPostsInFeed]);

  useScreenEffect(onRefreshPosts, {
    fetchOnMount: true,
    fetchOnSocketReconnect: true,
  });

  useEffect(() => {
    showTimingToast &&
      isLoading &&
      !postIds.length &&
      showSnackbar({
        title: t('home.taking_longer_than_expected'),
        variant: 'warning',
      });
    setShowTimingToast(false);
  }, [dispatch, showTimingToast, isLoading, t, postIds.length]);

  useEffect(() => {
    const isBirthDay = (route.params as {thereBirthday: boolean})
      ?.thereBirthday;

    isBirthDay && !isLoading && openCelebrationsPopup();
  }, [route.params, isLoading, navigation]);

  const onEndReached = useCallback(() => {
    getNextPage({includeGroupPosts: canViewGroupPostsInFeed});
  }, [getNextPage, canViewGroupPostsInFeed]);

  return (
    <>
      {isLoading && !postIds.length ? (
        <View style={styles.spinnerContainer}>
          <Spinner />
        </View>
      ) : (
        <FeedPosts
          hasNextPage={hasNextPage}
          pinnedPostIds={pinnedPostIds}
          postIds={postIds}
          refreshControl={
            <RefreshControl
              refreshing={isRefetching}
              onRefresh={onRefreshPosts}
            />
          }
          onEndReached={onEndReached}
        />
      )}
    </>
  );
}

export default Feed;
