import React, {useCallback} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {ListRow, Typography} from '@components';
import {Membership} from '@modules/chats/interfaces';
import {getUserAvatar} from '@modules/chats/utils';
import {useUserId} from '@redux/selectors';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  membership: Membership;
  currentHasYouReference?: boolean;
  isUserAdmin: boolean;
  onMemberActionsPress: (membership: Membership) => void;
  onRedirectToProfile: (userId: number) => void;
}

function MemberItem({
  membership,
  currentHasYouReference,
  isUserAdmin,
  onMemberActionsPress,
  onRedirectToProfile,
}: Props) {
  const {theme} = useTheme();
  const {t} = useTranslation();
  const userId = useUserId();
  const isCurrentUser = membership.user.id === userId;
  const avatar = getUserAvatar(membership.user, userId);
  const title =
    isCurrentUser && !currentHasYouReference ? t('chats.you') : avatar.title;

  const onItemPress = useCallback(() => {
    if (isCurrentUser) {
      return;
    }

    if (isUserAdmin) {
      onMemberActionsPress(membership);
    } else {
      onRedirectToProfile?.(membership.user.id);
    }
  }, [
    isCurrentUser,
    isUserAdmin,
    membership,
    onMemberActionsPress,
    onRedirectToProfile,
  ]);

  return (
    <ListRow onPress={onItemPress} style={styles.container}>
      <ListRow.Avatar {...avatar} />
      <ListRow.Title title={title} />
      <View style={styles.rightDescriptorContainer}>
        {membership.is_admin && (
          <Typography variant="xs" color={theme.text.neutral.lighter}>
            {t('chat.admin')}
          </Typography>
        )}
        {!isCurrentUser && <ListRow.SideContent withRightIcon />}
      </View>
    </ListRow>
  );
}

export default MemberItem;
