import { type FC, Fragment } from 'react';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { useAuth } from 'src/contexts/JWTContext';
import {
  type ConversationMessage as ConversationMessageType,
  type SystemMessages,
} from 'src/pages/dashboard/Conversations/types';
import { getSystemMessageText } from 'src/pages/dashboard/Conversations/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

type MessageSystemProps = {
  message: ConversationMessageType;
  systemMessages: SystemMessages;
};

type MessageSystemTextProps = {
  message: string;
};

const MessageSystemText: FC<MessageSystemTextProps> = ({ message }) => (
  <Stack
    sx={{
      width: '100%',
      maxWidth: '300px',
      alignSelf: 'center',
      justifyContent: 'center',
      alignItems: 'center',
      gap: 1,
    }}
  >
    <Typography
      variant="globalXXS"
      sx={{
        textAlign: 'center',
        color: theme => theme.palette.new.text.neutral.lighter,
      }}
    >
      {message}
    </Typography>
  </Stack>
);

const MessageSystem: FC<MessageSystemProps> = ({ message, systemMessages }) => {
  const { user: loggedUser } = useAuth();
  const { t } = useLokaliseTranslation(['chat', 'general']);
  const isUser = +message.user === loggedUser?.id;
  return (
    <>
      {systemMessages.map((systemMessage, index) => {
        const systemText = getSystemMessageText({
          text: message.text,
          t,
          username: message.username,
          systemMessages: [systemMessage],
          isUser,
          userId: loggedUser?.id,
        });

        if (!systemText) return null;

        return (
          <Fragment key={`${systemMessage.type}-${index}`}>
            <MessageSystemText message={systemText} />
          </Fragment>
        );
      })}
    </>
  );
};

export default MessageSystem;
