import { IconPinned } 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 { useAuth } from 'src/contexts/JWTContext';
import {
  type ConversationMessage,
  StateMessage,
} from 'src/pages/dashboard/Conversations/types';
import {
  compareIds,
  getMessageState,
  isAudioAttachment,
} from 'src/pages/dashboard/Conversations/utils';
import { formatMessageDate } from 'src/utils/date';
import { useLokaliseTranslation } from 'src/utils/i18n';

import MessageState from '../../shared/MessageState';

type MessageFooterProps = {
  message: ConversationMessage;
  isVisible: boolean;
  isDeleted: boolean;
  isSelfConversation: boolean;
  isPinnedMessage: boolean;
};
const MessageFooter = ({
  message,
  isVisible,
  isDeleted,
  isSelfConversation,
  isPinnedMessage,
}: MessageFooterProps) => {
  const theme = useTheme();
  const { t } = useLokaliseTranslation('chat');
  const { user: loggedUser } = useAuth();
  const isLoggedUserMessage = compareIds(message.user, loggedUser?.id);
  const firstAttachment = message.attachments?.[0];
  const isAudioMessage =
    !!firstAttachment && isAudioAttachment(firstAttachment);
  const isErrorSendMessage = message.state === StateMessage.ERROR;
  const messageState = getMessageState({
    readAt: message.hu_data?.read_status?.read_at,
    receivedAt: message.hu_data?.read_status?.received_at,
    messageState: message.state,
    isSelfConversation,
    isErrorSendMessage,
  });

  if (!isVisible) return null;

  return (
    <Stack
      sx={{
        flexDirection: 'row',
        alignItems: 'center',
        gap: 0.5,
        alignSelf: 'flex-end',
      }}
    >
      {isPinnedMessage && (
        <IconPinned
          color={theme.palette.new.text.neutral.lighter}
          size={16}
        />
      )}
      {message?.edited && !message?.hidden && (
        <Typography
          variant="globalXXS"
          fontWeight="fontWeightRegular"
          color={theme.palette.new.text.neutral.lighter}
          sx={{ fontStyle: 'italic' }}
        >
          {t('edit.edited')}
        </Typography>
      )}
      <Typography
        variant="globalXXS"
        fontWeight="fontWeightRegular"
        color={theme.palette.new.text.neutral.lighter}
        sx={{ marginRight: isAudioMessage && !isLoggedUserMessage ? 6 : 0 }}
      >
        {formatMessageDate(message.hu_data.message_ts, loggedUser)}
      </Typography>
      <MessageState
        state={messageState}
        theme={theme}
        isLoggedUserMessage={isLoggedUserMessage}
        hidden={isDeleted}
      />
    </Stack>
  );
};

export default MessageFooter;
