import React, {useCallback, useMemo, useRef} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {RouteProp, useFocusEffect, useRoute} from '@react-navigation/native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {useDispatch} from 'react-redux';
import {SceneMap, TabView, TabViewRoute} from '@components/TabView';
import {Language} from '@config/i18n';
import {markInteractiveProps} from '@config/perfomance';
import {useTabTracking} from '@hooks/useTabTracking';
import {useShowCallStatusBar} from '@modules/calls/store/selectors';
import Feed from '@modules/post/screens/Feed';
import Articles from '@modules/article/screens/Articles';
import {setArticleNotifications} from '@modules/article/redux';
import Marketplace from '@modules/marketplace/screens/Marketplace';
import {setScrollToTop} from '@modules/post/store';
import Groups from '@modules/group/screens/Groups';
import {
  setMarketplaceNotifications,
  useMarketplaceNotifications,
} from '@modules/marketplace/stores/useMarketplaceStore';
import {BottomTabNavigatorParamList} from '@navigation/BottomTabNavigator/interfaces';
import {useAppSelector} from '@redux/utils';
import {useInstanceProp, usePermissions} from '@redux/selectors';
import {
  clearModuleNotifications,
  ModulesNotifications,
} from '@shared/notifications';
import {useActivePostsStore} from '@shared/stores/useActivePostsStore';
import {
  capitalize,
  fetchModulesNotifications,
  HOME_TAB_MODULES,
} from '@shared/utils';
import {Screens} from '@shared/constants';
import {useTheme} from '@shared/theme';
import {useCommunityFeature} from '@stores/communityFeatures';

import {HomeTab} from './interfaces';
import {getContainerStyle, styles} from './styles';
import HomeNavbar from './components/HomeNavbar';

const renderScene = SceneMap({
  [HomeTab.FEED]: Feed,
  [HomeTab.ARTICLES]: Articles,
  [HomeTab.GROUPS]: Groups,
  [HomeTab.MARKETPLACE]: Marketplace,
});

function HomeScreen() {
  const {t, i18n} = useTranslation();
  const dispatch = useDispatch();
  const {top} = useSafeAreaInsets();
  const showCallStatusBar = useShowCallStatusBar();
  const {theme} = useTheme();
  const {VIEW_POSTS, VIEW_ARTICLES, VIEW_MARKETPLACE, VIEW_GROUPS} =
    usePermissions();
  const deferRedBubbles = useCommunityFeature('DEFER_RED_BUBBLES');
  const hasFetchedHomeBubbles = useRef(false);

  useFocusEffect(
    useCallback(() => {
      if (!hasFetchedHomeBubbles.current && deferRedBubbles) {
        fetchModulesNotifications(HOME_TAB_MODULES);
        hasFetchedHomeBubbles.current = true;
      }
    }, [deferRedBubbles]),
  );
  const {setScreenActiveKey} = useActivePostsStore();
  const moduleNames = useInstanceProp('moduleNames');
  const articleNotifications = useAppSelector(
    ({article}) => article.articleNotifications,
  );
  const marketplaceNotifications = useMarketplaceNotifications();
  const groupNotifications = useAppSelector(
    ({group}) => group.groupNotifications,
  );
  const showTabBar =
    [VIEW_POSTS, VIEW_ARTICLES, VIEW_GROUPS, VIEW_MARKETPLACE].filter(Boolean)
      .length >= 2;
  const containerStyle = useMemo(
    () => getContainerStyle(showCallStatusBar, top),
    [showCallStatusBar, top],
  );

  const routes = useMemo(() => {
    const availableTabs = [];
    VIEW_POSTS &&
      availableTabs.push({
        key: HomeTab.FEED,
        title:
          capitalize(moduleNames?.[i18n.language as Language]?.FEED, false) ||
          t('home.wall'),
      });
    VIEW_GROUPS &&
      availableTabs.push({
        key: HomeTab.GROUPS,
        title:
          capitalize(moduleNames?.[i18n.language as Language]?.GROUPS, false) ||
          t('group.groups'),
        badge: groupNotifications,
      });
    VIEW_ARTICLES &&
      availableTabs.push({
        key: HomeTab.ARTICLES,
        title:
          capitalize(
            moduleNames?.[i18n.language as Language]?.ARTICLES,
            false,
          ) || t('home.articles'),
        badge: articleNotifications,
      });
    VIEW_MARKETPLACE &&
      availableTabs.push({
        key: HomeTab.MARKETPLACE,
        title: t('marketplace.marketplace'),
        badge: marketplaceNotifications,
      });
    return availableTabs as TabViewRoute[];
  }, [
    VIEW_ARTICLES,
    VIEW_GROUPS,
    VIEW_MARKETPLACE,
    VIEW_POSTS,
    articleNotifications,
    groupNotifications,
    marketplaceNotifications,
    moduleNames,
    t,
    i18n,
  ]);

  const route =
    useRoute<RouteProp<BottomTabNavigatorParamList, Screens.HOME>>();
  const homeTab = route.params?.homeTab;

  const initialIndex = useMemo(() => {
    if (!homeTab) {
      return 0;
    }
    const idx = routes.findIndex(r => r.key === homeTab);
    return Math.max(idx, 0);
  }, [homeTab, routes]);

  const trackTabUse = useTabTracking();

  const handleTabPress = useCallback(
    (key: string, selectedTab: string) => {
      switch (key) {
        case HomeTab.FEED:
          selectedTab === HomeTab.FEED && dispatch(setScrollToTop(true));
          setScreenActiveKey('feed');
          break;
        case HomeTab.ARTICLES:
          articleNotifications &&
            clearModuleNotifications(ModulesNotifications.ARTICLE);
          dispatch(setArticleNotifications(0));
          setScreenActiveKey('articles');
          break;
        case HomeTab.MARKETPLACE:
          marketplaceNotifications &&
            clearModuleNotifications(ModulesNotifications.MARKETPLACE);
          setMarketplaceNotifications(0);
          setScreenActiveKey('marketplace');
          break;
        case HomeTab.GROUPS:
          setScreenActiveKey('groups');
      }
      trackTabUse(key);
    },
    [
      trackTabUse,
      dispatch,
      setScreenActiveKey,
      articleNotifications,
      marketplaceNotifications,
    ],
  );

  return (
    <View
      style={[
        styles.container,
        containerStyle,
        {backgroundColor: theme.background.layout.tertiary},
      ]}
      {...markInteractiveProps}>
      <HomeNavbar />
      <TabView
        initialIndex={initialIndex}
        routes={routes}
        renderScene={renderScene}
        swipeEnabled={false}
        showTabBar={showTabBar}
        onTabPress={handleTabPress}
        tabBarStyle={[
          styles.tabView,
          {
            borderColor: theme.border.neutral.default,
            backgroundColor: theme.background.layout.tertiary,
          },
        ]}
        lazy
      />
    </View>
  );
}

export default HomeScreen;
