import React, {FC, memo, useMemo, useRef} from 'react';
import {TouchableOpacity, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {Typography, Avatar, Checkbox, SNACKBAR_DURATION} from '@components';
import {getChatAvatar, getUserAvatar} from '@modules/chats/utils';
import {ChatUser, Conversation} from '@modules/chats/interfaces';
import {MAX_FORWARD_ITEMS} from '@modules/chats/constants';
import {showSnackbar} from '@redux/dispatchers';
import {useTheme} from '@shared/theme';

import {styles} from './styles';
import {SelectedItem} from '../../interfaces';

interface Props {
  userId: number;
  item: Conversation | ChatUser;
  avatar?: ReturnType<typeof getChatAvatar>;
  isSelected: boolean;
  disabled: boolean;
  onSelect: (item: SelectedItem) => void;
}

export const ListItem: FC<Props> = memo(
  ({item, userId, isSelected, disabled, onSelect}) => {
    const {theme} = useTheme();
    const bannerIsVisible = useRef(false);
    const {t} = useTranslation();
    const isUser = (item as ChatUser).hu_data?.member !== undefined;
    const name = isUser
      ? (item as ChatUser).hu_data.member.first_name
      : (item as Conversation).name ||
        (item as Conversation).other_user?.first_name;

    const avatar = useMemo(() => {
      if (isUser) {
        return getUserAvatar((item as ChatUser).hu_data.member, userId);
      }
      return getChatAvatar(item as Conversation, userId);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const onSelectItem = () => {
      if (disabled) {
        if (bannerIsVisible.current) {
          return;
        }

        bannerIsVisible.current = true;

        // Show warning banner
        showSnackbar({
          title: t('chat.forward.warning', {
            count: MAX_FORWARD_ITEMS,
          }),
          variant: 'info',
        });

        // Enable banner when the snackbar is hidden
        setTimeout(() => {
          bannerIsVisible.current = false;
        }, SNACKBAR_DURATION);
      } else {
        onSelect({id: item.id, isUser, name: name || ''});
      }
    };

    return (
      <TouchableOpacity
        onPress={onSelectItem}
        style={styles.container}
        activeOpacity={1}>
        <View pointerEvents="none" style={styles.checkboxContainer}>
          <Checkbox disabled={disabled} checked={isSelected} />
        </View>
        <Avatar {...avatar} />
        <Typography
          variant="xs"
          weight="semiBold"
          color={theme.text.neutral.default}>
          {avatar.title}
        </Typography>
      </TouchableOpacity>
    );
  },
);
