import React, {memo} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useNetInfo} from '@react-native-community/netinfo';
import {IconPlus} from '@tabler/icons-react-native';
import {useNavigation} from '@react-navigation/native';
import {IconButton, Title} from '@components';
import {closeAllSwipeables} from '@components/RNSwipeable';
import {AnimatedInfoHeader} from '@modules/chats/components';
import {
  useIsConversationsLoading,
  useIsFetchingEvents,
} from '@modules/chats/store';
import {Screens} from '@shared/constants';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  hideCreateButton?: boolean;
}

function ChatHomeHeader({hideCreateButton}: Props) {
  const {t} = useTranslation();
  const navigation = useNavigation();
  const {theme} = useTheme();
  const {isInternetReachable} = useNetInfo();
  const isLoading = useIsConversationsLoading();
  const isFetchingEvents = useIsFetchingEvents();
  const isOffline = isInternetReachable === false;
  const showUpdating = isFetchingEvents && !isLoading; // Show updating only if Skeleton is not visible
  const text = isOffline
    ? t('chat.net_info.offline')
    : showUpdating
    ? t('chat.net_info.syncing')
    : null;
  const show = isOffline || showUpdating;

  const onNewChatPress = () => {
    navigation.navigate(Screens.CHATS_NEW);
  };

  return (
    <View
      style={[styles.header, {borderColor: theme.border.neutral.default}]}
      onTouchStart={closeAllSwipeables}>
      <Title title={t('chat.chats')} center />
      <View style={styles.infoContainer}>
        {show && <AnimatedInfoHeader text={text} showSpinner />}
      </View>
      {!hideCreateButton && (
        <View style={styles.newChatButtonContainer}>
          <IconButton
            Icon={IconPlus}
            accessibilityLabel={t('chat.new_chat')}
            onPress={onNewChatPress}
          />
        </View>
      )}
    </View>
  );
}

export default memo(ChatHomeHeader);
