import React, {memo, useMemo} from 'react';
import {StyleProp, ViewStyle} from 'react-native';
import {IconFolder} from '@tabler/icons-react-native';
import {Badge, ListRow} from '@components/_HuGo';
import {useTheme} from '@shared/theme';

import {File} from '../../interfaces';
import {getItemTitle} from '../../utils';
import {styles} from './styles';
import {useFolderListeners} from './useFolderListeners';

interface Props {
  item: File;
  onPress?: (id: number, name: string) => void;
  searchTerm?: string;
  style?: StyleProp<ViewStyle>;
}

function Folder({item: {name, id}, onPress, searchTerm, style}: Props) {
  const {theme} = useTheme();
  const folderTitle = useMemo(
    () => getItemTitle(name, searchTerm),
    [name, searchTerm],
  );
  const {unreadDocuments, refreshFolderNotifications} = useFolderListeners(id);

  const onPressFolder = () => {
    refreshFolderNotifications();
    onPress?.(id, name);
  };

  return (
    <ListRow
      backgroundColor={theme.background.layout.tertiary}
      onPress={onPressFolder}
      style={[styles.container, style]}>
      <ListRow.Avatar Icon={IconFolder} />
      <ListRow.Title title={folderTitle} titleNumberOfLines={2} />
      {/* The number 1 is for maintain the width of the badge */}
      <Badge show={!!unreadDocuments} value={unreadDocuments || 1} />
      <ListRow.SideContent withRightIcon />
    </ListRow>
  );
}

export default memo(Folder);
