import { IconAlertCircle, IconBan } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import { useSearchHighlight } from 'src/pages/dashboard/Conversations/contexts/SearchHighlightContext';
import { type HighlightedSpan } from 'src/pages/dashboard/Conversations/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import TypographyTagAndLinkSensitive from './TypographyTagAndLinkSensitive';

type MessageTextProps = {
  isSystemMessage: boolean;
  text: string;
  isKnownBlock: boolean;
  isDeleted: boolean;
  isLoggedUser: boolean;
  messageId: string;
  highlightedSpans?: HighlightedSpan[];
};

const MessageText = ({
  isKnownBlock,
  isSystemMessage,
  text,
  isDeleted = false,
  isLoggedUser,
  messageId,
  highlightedSpans = [],
}: MessageTextProps) => {
  const { t } = useLokaliseTranslation('chat');
  const theme = useTheme();
  const { searchQuery, matchedMessageIds } = useSearchHighlight();
  const highlightQuery = matchedMessageIds.includes(messageId)
    ? searchQuery
    : '';

  if (isSystemMessage && !isKnownBlock) {
    return (
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          gap: 0.5,
        }}
      >
        <IconAlertCircle
          color={theme.palette.new.text.neutral.lighter}
          size={18}
        />
        <Typography
          variant="globalS"
          sx={{ whiteSpace: 'pre-wrap' }}
          fontStyle="italic"
        >
          {t('messages.block_not_available')}
        </Typography>
      </Stack>
    );
  }

  if (isDeleted) {
    return (
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          gap: 0.5,
        }}
      >
        <IconBan
          color={theme.palette.new.text.neutral.lighter}
          size={16}
        />
        <Typography
          variant="globalS"
          fontStyle="italic"
          color={theme.palette.new.text.neutral.lighter}
          sx={{ whiteSpace: 'pre-wrap' }}
        >
          {isLoggedUser
            ? t('delete.message_deleted_you')
            : t('delete.message_deleted_user')}
        </Typography>
      </Stack>
    );
  }
  return (
    <TypographyTagAndLinkSensitive
      variant="globalS"
      sx={{ whiteSpace: 'pre-wrap' }}
      highlightQuery={highlightQuery}
      highlightedSpans={highlightedSpans}
    >
      {text}
    </TypographyTagAndLinkSensitive>
  );
};

export default MessageText;
