import React, {memo} from 'react';
import {View} from 'react-native';
import {Typography} from '@components';
import {
  Block,
  SystemMessage as SystemMessageType,
} from '@modules/chats/interfaces';
import {useBlockTextHandler} from '@modules/chats/hooks';
import {getMessageMargins} from '@modules/chats/utils';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  item: SystemMessageType;
}

const BlockRenderer = ({
  block,
  userId,
  username,
}: {
  block: Block;
  userId: string;
  username: string;
}) => {
  const {theme} = useTheme();
  const textToDisplay = useBlockTextHandler({
    block: block,
    emitterUserId: Number(userId),
    emitterUsername: username,
  });

  return (
    <Typography
      color={theme.text.neutral.lighter}
      variant="xxs"
      style={styles.text}
      align="center"
      numberOfLines={1}
      allowFontScaling={false}
      maxFontSizeMultiplier={100}
      textBreakStrategy="simple">
      {textToDisplay}
    </Typography>
  );
};

function SystemMessage({item}: Props) {
  const margins = getMessageMargins(item);
  return (
    <View style={[styles.container, margins]}>
      {item.data.blocks.map(block => (
        <BlockRenderer
          key={block.type}
          block={block}
          userId={item.data.userId}
          username={item.data.username}
        />
      ))}
    </View>
  );
}

export default memo(SystemMessage);
