import React, {memo, useCallback, useMemo} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {useNavigation} from '@react-navigation/native';
import {useNetInfo} from '@react-native-community/netinfo';
import {BackButton, ListRow, Typography} from '@components';
import {useGoBack} from '@hooks/useGoBack';
import {CallStatusBar} from '@modules/calls/components/CallStatusBar';
import {useShowCallStatusBar} from '@modules/calls/store/selectors';
import {useMessagesSearch, useShallowConversation} from '@modules/chats/store';
import {
  CHAT_HEADER_AVATAR_SIZE,
  getChatAvatar,
  getChatImage,
} from '@modules/chats/utils';
import {ChatUserStatus} from '@modules/chats/interfaces';
import {AnimatedInfoHeader} from '@modules/chats/components';
import {useGroupInfo} from '@modules/chats/hooks';
import {useIsChatUserDeactivated} from '@modules/chats/store/zustand/useGroups';
import {persistedUserId} from '@services/localStorage';
import {Screens} from '@shared/constants';
import {useTheme} from '@shared/theme';

import {CallButtons} from './components/CallButtons';
import {styles} from './styles';
import {ChatMessagesSearchBar} from '../ChatMessagesSearch';
import {UserOffAvatar} from './components/UserOffAvatar';

interface Props {
  channel: string;
}

const DISABLED_USER_ICON = '⛔';

const ChatHeaderComponent = ({channel}: Props) => {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {top} = useSafeAreaInsets();
  const navigation = useNavigation();
  const {goBack} = useGoBack();
  const conversation = useShallowConversation(channel, state => ({
    name: state.name,
    is_channel: state.is_channel,
    is_im: state.is_im,
    other_user: state.other_user,
    picture_url: state.picture_url,
  }));
  const {shortGroupMembers} = useGroupInfo(channel);
  const {isInternetReachable} = useNetInfo();
  const showCallStatusBar = useShowCallStatusBar();
  const isOffline = isInternetReachable === false;
  const user = conversation?.other_user;
  const userUnavailable =
    user?.status === ChatUserStatus.Deactivated || !!user?.deleted_at;
  const avatar = useMemo(
    () => getChatAvatar(conversation, persistedUserId!),
    [conversation],
  );
  const avatarUrl = getChatImage.avatar(avatar.url, {
    avatarSize: CHAT_HEADER_AVATAR_SIZE,
  });
  const isIm = conversation?.is_im;
  const isChannel = conversation?.is_channel;

  const isUserDeactivated = useIsChatUserDeactivated(channel);

  const showLoader = !!isOffline;
  const text = isOffline ? t('chat.net_info.offline') : null;

  const isSearchVisible = useMessagesSearch(state => state.isSearchVisible);
  const memoizedStyles = useMemo(() => {
    const safeTopMargin = showCallStatusBar ? 0 : top;
    const backgroundColor = theme.background.layout.tertiary;

    return {
      container: [styles.container, {backgroundColor}],
      content: [
        styles.content,
        {marginTop: safeTopMargin},
        {
          backgroundColor,
          borderColor: theme.border.neutral.default,
        },
      ],
      spacer: [
        styles.spacerStyle,
        {marginTop: safeTopMargin},
        {backgroundColor},
      ],
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [showCallStatusBar, top]);

  const onDetailPress = useCallback(() => {
    if (isIm && userUnavailable) {
      return;
    }

    navigation.navigate(Screens.CHATS_CHAT_INFO, {
      id: channel,
    });
  }, [isIm, userUnavailable, navigation, channel]);

  const membersNames = useMemo(() => {
    const sortedMembers = [...shortGroupMembers].sort((a, b) => {
      return a.user.first_name.localeCompare(b.user.first_name);
    });
    const names = sortedMembers.reduce<string[]>((acc, member) => {
      if (member.user.id === persistedUserId) {
        return acc;
      }
      acc.push(member.user.first_name);
      return acc;
    }, []);

    names.push(t('chats.you'));

    return names.join(', ');
  }, [shortGroupMembers, t]);

  const useName = useMemo(() => {
    if (
      isUserDeactivated &&
      avatar.title.lastIndexOf(DISABLED_USER_ICON) !== -1
    ) {
      // Remove this icon only in this component
      return avatar.title.replace(DISABLED_USER_ICON, '').trim();
    }
    return avatar.title;
  }, [isUserDeactivated, avatar.title]);

  return (
    <>
      <View style={memoizedStyles.container}>
        {showCallStatusBar && <CallStatusBar />}
        {isSearchVisible ? (
          <ChatMessagesSearchBar channel={channel} />
        ) : (
          <View style={memoizedStyles.content}>
            <BackButton onPress={goBack} />
            <View style={styles.middle}>
              <ListRow
                backgroundColor={theme.background.layout.tertiary}
                onPress={onDetailPress}
                accessible={false}>
                {isUserDeactivated ? (
                  <UserOffAvatar />
                ) : (
                  <ListRow.Avatar {...avatar} url={avatarUrl} />
                )}
                <View style={styles.centerInfo}>
                  <ListRow.Title
                    title={useName}
                    flex={false}
                    style={styles.fullWidth}
                    description={
                      isUserDeactivated
                        ? t('general.deactivated_collaborator')
                        : undefined
                    }
                  />
                  {isChannel && !showLoader ? (
                    <Typography
                      variant="xxs"
                      numberOfLines={1}
                      lineBreakMode="tail"
                      color={theme.text.neutral.lighter}
                      style={styles.fullWidth}>
                      {membersNames}
                    </Typography>
                  ) : (
                    showLoader && <AnimatedInfoHeader text={text} showSpinner />
                  )}
                </View>
                <CallButtons channel={channel} />
              </ListRow>
            </View>
          </View>
        )}
      </View>
      <View style={memoizedStyles.spacer} />
    </>
  );
};

export const ChatHeader = memo(ChatHeaderComponent);
