import { memo } from 'react';

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

import HuPills from '@material-hu/components/design-system/Pills';

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

import ConversationMessage from './ConversationMessage';

type ConversationMessageBlockProps = {
  message: ConversationMessageType;
  messagePrev: ConversationMessageType;
  nextMessage: ConversationMessageType;
  members: Member[];
  position: number;
  unreadCount: number;
  latestRead?: string;
  hasPreviousPage: boolean;
  isGroupConversation: boolean;
  isSelfConversation: boolean;
};

const ConversationMessageBlock = (props: ConversationMessageBlockProps) => {
  const {
    message,
    messagePrev,
    nextMessage,
    members,
    position,
    unreadCount,
    latestRead,
    hasPreviousPage,
    isGroupConversation,
    isSelfConversation,
  } = props;
  const { t } = useLokaliseTranslation(['general', 'chat']);
  const { user } = useAuth();

  const showToDate = getDateToShow(
    t,
    hasPreviousPage,
    message?.hu_data?.message_ts,
    messagePrev?.hu_data?.message_ts,
    user,
  );

  const isUnreadDividerPosition =
    unreadCount > 0 && messagePrev?.hu_data?.message_ts === latestRead;
  const isSameUserAsPrev =
    messagePrev?.user === message.user &&
    !message?.blocks &&
    !messagePrev?.blocks;
  const spacing = isSameUserAsPrev ? 0.5 : 1;

  return (
    <Stack sx={{ mt: position === 0 ? 0 : spacing, px: 2 }}>
      {showToDate && (
        <Stack sx={{ alignItems: 'center', mb: 1 }}>
          <HuPills
            hasIcon={false}
            label={showToDate}
            size="medium"
            type="neutral"
          />
        </Stack>
      )}

      {isUnreadDividerPosition && (
        <Stack
          sx={{
            alignItems: 'center',
            mb: 1,
          }}
        >
          <HuPills
            hasIcon={false}
            label={getUnreadMessagesLabel(t, unreadCount)}
            size="medium"
            type="info"
          />
        </Stack>
      )}

      <ConversationMessage
        message={message}
        members={members}
        isGroupConversation={isGroupConversation}
        prevMessage={messagePrev}
        nextMessage={nextMessage}
        isSelfConversation={isSelfConversation}
      />
    </Stack>
  );
};

export default memo(ConversationMessageBlock);
