import React from 'react';
import Chip from '@mui/material/Chip';
import Typography from '@mui/material/Typography';

interface RichMessageTextProps {
  message: string;
  messageParameters?: Record<string, any>;
  isOwnMessage?: boolean;
}

const RichMessageText: React.FC<RichMessageTextProps> = ({ message, messageParameters, isOwnMessage }) => {
  const parts = message.split(/(\{[^}]+\})/);

  const elements = parts.map((part, i) => {
    const match = part.match(/^\{([^}]+)\}$/);
    if (!match) {
      return part ? <span key={i}>{part}</span> : null;
    }

    const key = match[1];
    const param = messageParameters?.[key];
    if (!param) return <span key={i}>{part}</span>;

    const { type, name, id } = param;

    if (type === 'user' || type === 'guest' || type === 'call' || type === 'user-group') {
      return (
        <Chip
          key={i}
          label={`@${name ?? id}`}
          size="small"
          sx={{
            height: 18,
            fontSize: '0.75rem',
            mx: 0.25,
            bgcolor: isOwnMessage ? 'rgba(255,255,255,0.2)' : 'action.hover',
            color: 'inherit',
            '& .MuiChip-label': { px: 0.75 },
            verticalAlign: 'middle',
          }}
        />
      );
    }

    if (type === 'highlight' || key === 'actor') {
      return <strong key={i}>{name ?? id}</strong>;
    }

    return <span key={i}>{name ?? id ?? key}</span>;
  });

  return (
    <Typography
      variant="body2"
      component="span"
      sx={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', display: 'block' }}
    >
      {elements}
    </Typography>
  );
};

export default RichMessageText;
