import React, {memo} from 'react';
import {View} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {IconBook, IconChevronRight} from '@tabler/icons-react-native';
import {Avatar, AvatarSize, ListItem, Pressable, HtmlRender} from '@components';
import {IconTypes} from '@interfaces/icon';
import {KnowledgeLibraryListItem} from '@modules/libraries/interfaces';
import {Screens} from '@shared/constants';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  data: KnowledgeLibraryListItem;
}

function LibraryItem({data}: Props) {
  const navigation = useNavigation();
  const {theme, iconSizes} = useTheme();

  const {title, textContent} = data.highlights || {};

  const titleTagsStyles = {
    div: {...styles.title, color: theme.text.neutral.default},
    span: {backgroundColor: theme.border.neutral.brand},
  };
  const textContentTagsStyles = {
    div: {...styles.description, color: theme.text.neutral.lighter},
    span: {backgroundColor: theme.border.neutral.brand},
  };

  const avatarProps = {
    rounded: false,
    Icon: IconBook,
    size: 'sm' as AvatarSize,
    ...(data.icon.type === IconTypes.IMAGE
      ? {url: data.icon.value}
      : {emoji: data.icon.value}),
  };

  const onPress = () =>
    navigation.navigate(Screens.KNOWLEDGE_LIBRARY, {id: data.id});

  // TODO replace highlight item with ListRow
  return data.highlights ? (
    <Pressable
      backgroundColor={theme.background.layout.default}
      onPress={onPress}
      style={[
        styles.container,
        styles.item,
        {borderColor: theme.border.neutral.default},
      ]}>
      <View style={styles.itemContent}>
        <Avatar {...avatarProps} />
        <View style={styles.content}>
          <HtmlRender
            html={`<div>${title.length ? title[0] : data.title}</div>`}
            tagsStyles={titleTagsStyles}
          />
          {!!textContent.length && (
            <HtmlRender
              html={`<div>${textContent[0]}</div>`}
              tagsStyles={textContentTagsStyles}
            />
          )}
        </View>
      </View>
      <IconChevronRight
        size={iconSizes.x6}
        color={theme.text.neutral.default}
      />
    </Pressable>
  ) : (
    <ListItem
      avatar={avatarProps}
      onItemPress={onPress}
      title={data.title}
      presentation="card"
      withRightIcon
      style={styles.item}
    />
  );
}

export default memo(LibraryItem);
