import React, {memo, useMemo} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {Typography} from '@components/index';
import {useBlockTextHandler} from '@modules/chats/hooks';
import {ConversationLatest, SystemBlockTypes} from '@modules/chats/interfaces';
import {usePrefixIconAndText} from '@modules/chats/hooks/usePrefixIconAndText';
import {persistedUserId} from '@services/localStorage';
import {useTheme} from '@shared/theme';

import {styles} from './styles';
import {MessageStatusDisplayer} from '../MessageStatusDisplayer';

interface Props {
  message?: Nullable<ConversationLatest>;
  isChannel: boolean;
}

function LastMessageComponent({message, isChannel}: Props) {
  const {t} = useTranslation();
  const {theme, iconSizes} = useTheme();
  const sentByCurrentUser = Number(message?.user) === Number(persistedUserId);
  const emitterName = message?.username.split(' ')?.at(0) || '';
  const systemBlock = message?.blocks?.find(block =>
    SystemBlockTypes.includes(block.type),
  );
  const systemMessage = useBlockTextHandler({
    block: systemBlock,
    emitterUserId: Number(message?.user),
    emitterUsername: emitterName || '',
  });
  const isDeleted = !!message?.hidden;
  const showMessageStatus = !isDeleted && !systemMessage;
  const {PrefixIcon, defaultText} = usePrefixIconAndText({
    assets: message?.attachments,
    pendingAssets: message?.pendingAssets,
    isDeleted,
  });
  const showPrefix = showMessageStatus || !!PrefixIcon;

  const text = useMemo(() => {
    if (systemMessage) {
      return systemMessage;
    }

    let result = isChannel
      ? `${sentByCurrentUser ? t('chat.you') : emitterName}: `
      : '';

    if (isDeleted) {
      result =
        result +
        t(
          sentByCurrentUser
            ? 'chat.delete.message_deleted_you'
            : 'chat.delete.message_deleted_user',
        );
    } else if (message?.formatted_text || message?.text) {
      result = result + (message.formatted_text || message.text);
    } else if (defaultText) {
      result = result + defaultText;
    } else {
      result = result + t('chat.messages.unsupported');
    }

    return result;
  }, [
    systemMessage,
    isChannel,
    sentByCurrentUser,
    emitterName,
    isDeleted,
    defaultText,
    message?.formatted_text,
    message?.text,
    t,
  ]);

  return message ? (
    <View style={styles.container}>
      <Typography
        numberOfLines={2}
        variant="xs"
        color={theme.text.neutral.lighter}
        maxFontSizeMultiplier={100}
        key={`${message.status}-${message.deliver_status?.read_at}-${message.deliver_status?.received_at}`}
        fontStyle={isDeleted ? 'italic' : undefined}>
        {showPrefix && (
          <>
            {showMessageStatus && (
              <MessageStatusDisplayer
                status={message?.status}
                deliverStatus={message?.deliver_status}
                style={styles.icon}
                withRightSpace
              />
            )}
            {PrefixIcon && (
              <>
                <PrefixIcon
                  color={theme.text.neutral.lighter}
                  size={iconSizes.x4}
                  style={styles.icon}
                />
                {
                  // This space is needed!!!
                  ' '
                }
              </>
            )}
          </>
        )}
        {text.trim()}
      </Typography>
    </View>
  ) : null;
}

export const LastMessage = memo(LastMessageComponent);
