import { type FC } from 'react';

import Stack from '@material-hu/mui/Stack';
import { alpha, useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';

import MessageRepliedAttachments from 'src/pages/dashboard/Conversations/components/ConversationsThread/ConversationMessage/MessageRepliedAttachments';
import { type BloackMessageReplied } from 'src/pages/dashboard/Conversations/types';

import { useScrollToMessageConversation } from '../../../contexts/ScrollToMessageConversationContext';
import { useSearchHighlight } from '../../../contexts/SearchHighlightContext';

import TypographyTagAndLinkSensitive from './TypographyTagAndLinkSensitive';

type MessageReplied = {
  messageReply: BloackMessageReplied;
  isLoggedUser: boolean;
  messageId: string;
};

const MessageReplied: FC<MessageReplied> = props => {
  const { messageReply, isLoggedUser, messageId } = props;
  const theme = useTheme();
  const { scrollToMessage } = useScrollToMessageConversation();
  const { searchQuery, matchedMessageIds } = useSearchHighlight();
  const highlightQuery = matchedMessageIds.includes(messageId)
    ? searchQuery
    : '';

  const hasAttachments = !!messageReply?.assets.length;

  const userSender = messageReply?.sender_membership?.user?.hu_data?.member;

  const userName = `${userSender?.first_name} ${userSender?.last_name} `;

  const handleOnClick = () => {
    scrollToMessage(messageReply.message_replied_id);
  };

  const backgroundColor = isLoggedUser
    ? theme.palette.new.graphics.brand[100]
    : theme.palette.new.background.layout.default;
  if (hasAttachments) {
    return (
      <MessageRepliedAttachments
        onClick={handleOnClick}
        text={messageReply.text}
        userName={userName}
        files={messageReply?.assets}
        sxContainer={{
          backgroundColor,
        }}
        highlightedSpans={messageReply?.highlighted_spans}
      />
    );
  }

  return (
    <HuCardContainer
      onClick={handleOnClick}
      sx={{
        width: '100%',
        borderRadius: 1,
        border: 0,
        backgroundColor,
        '& .MuiCardContent-root': {
          padding: 1,
        },
      }}
    >
      <Stack>
        <Typography
          variant="globalXXS"
          fontWeight="fontWeightSemiBold"
        >
          {userName}
        </Typography>
        <TypographyTagAndLinkSensitive
          variant="globalXXS"
          disableLink
          highlightQuery={highlightQuery}
          highlightedSpans={messageReply?.highlighted_spans}
        >
          {messageReply.text}
        </TypographyTagAndLinkSensitive>
      </Stack>
    </HuCardContainer>
  );
};

export default MessageReplied;
