import React, {useCallback} from 'react';
import {TouchableOpacity} from 'react-native';
import {BaseUser} from '@components/UsersSectionList/interfaces';
import {useThrottleCallback} from '@hooks/useThrottleCallback';
import {COLORS} from '@shared/colors';
import {Opacity} from '@shared/constants';
import {AvatarWithName} from '@components/Image';
import Checkbox from '@components/Checkbox';
import ActivityIndicator from '@components/ActivityIndicator';

import {styles} from './styles';

interface Props<T extends BaseUser> {
  item: T;
  showCheckbox?: boolean;
  isChecked?: (item: T) => boolean;
  onPress?: (item: T) => void;
  withLoading?: boolean;
  avoidDebouncePress?: boolean;
}

function UsersSectionListItem<T extends BaseUser>({
  item,
  showCheckbox,
  isChecked,
  onPress,
  withLoading,
  avoidDebouncePress,
}: Props<T>) {
  const handlePressItem = useCallback(() => {
    onPress?.(item);
  }, [item, onPress]);

  const debouncePress = useThrottleCallback(handlePressItem);

  const checked = !!isChecked?.(item);

  const onPressItem =
    showCheckbox || avoidDebouncePress ? handlePressItem : debouncePress;

  return (
    <TouchableOpacity
      activeOpacity={Opacity.FULL}
      style={styles.container}
      disabled={!onPress}
      onPress={onPressItem}>
      {showCheckbox && (
        <Checkbox
          checked={checked}
          color={checked ? COLORS.GREEN_EIGHT : COLORS.GRAY_THIRTY_TWO}
          size={28}
          onPress={onPressItem}
          containerStyle={styles.checkboxContainer}
        />
      )}
      <AvatarWithName
        url={item.profilePicture}
        name={item}
        size="lg"
        style={styles.flexGrow}
      />
      {withLoading && <ActivityIndicator style={styles.loadingContainer} />}
    </TouchableOpacity>
  );
}

export default UsersSectionListItem;
