import { useEffect, useState } from 'react';
import { Image, Text, TouchableOpacity, View } from 'react-native';
import { useStyles } from './styles';
import { CategoryRepository } from '@amityco/ts-sdk-react-native';
import { useNavigation } from '@react-navigation/native';
import { useFile } from '../../hooks';
import { ImageSizeState } from '../../enums';
import { defaultAvatarUri, defaultCommunityAvatarUri } from '../../../core/assets';
export default function SearchItem({
  target,
  onPress,
  userProfileNavigateEnabled = true
}) {
  const styles = useStyles();
  const {
    getImage
  } = useFile();
  const [isChecked, setIsChecked] = useState(false);
  const [avatar, setAvatar] = useState(defaultAvatarUri);
  const [categoryName, setCategoryName] = useState('');
  const navigation = useNavigation();
  const handleToggle = () => {
    setIsChecked(!isChecked);
    if (onPress) {
      onPress(target);
    }
    if (userProfileNavigateEnabled) {
      if (target.targetType === 'community') {
        navigation.navigate('CommunityProfilePage', {
          communityId: target.targetId
        });
      } else {
        navigation.navigate('UserProfile', {
          userId: target.targetId
        });
      }
    }
  };
  useEffect(() => {
    if (!(target !== null && target !== void 0 && target.avatarFileId)) return;
    (async () => {
      const fileUrl = await getImage({
        fileId: target === null || target === void 0 ? void 0 : target.avatarFileId,
        imageSize: ImageSizeState.small
      });
      const avatarUrl = fileUrl ? fileUrl : (target === null || target === void 0 ? void 0 : target.targetType) === 'community' ? defaultCommunityAvatarUri : defaultAvatarUri;
      setAvatar(avatarUrl);
    })();
  }, [getImage, target === null || target === void 0 ? void 0 : target.avatarFileId, target === null || target === void 0 ? void 0 : target.targetType]);
  useEffect(() => {
    getCategory();
  }, [target.categoryIds]);
  async function getCategory() {
    if (target.categoryIds) {
      const {
        data: category
      } = await CategoryRepository.getCategory(target.categoryIds[0]);
      category && setCategoryName(category.name);
    }
  }
  return /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.listItem,
    onPress: handleToggle
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.leftContainer
  }, /*#__PURE__*/React.createElement(Image, {
    style: styles.avatar,
    source: {
      uri: avatar
    }
  }), /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(Text, {
    numberOfLines: 1,
    style: styles.itemText
  }, target === null || target === void 0 ? void 0 : target.displayName), (target === null || target === void 0 ? void 0 : target.targetType) === 'community' && /*#__PURE__*/React.createElement(Text, {
    style: styles.categoryText
  }, categoryName))));
}
//# sourceMappingURL=index.js.map