import { type FC } from 'react';

import { IconPinned } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import HuAvatar from '@material-hu/components/design-system/Avatar';

import TypographyTagAndLinkSensitive from 'src/pages/dashboard/Conversations/components/ConversationsThread/ConversationMessage/TypographyTagAndLinkSensitive';
import AttachmentDescription from 'src/pages/dashboard/Conversations/components/shared/AttachmentDescription';
import AttachmentThumbnail from 'src/pages/dashboard/Conversations/components/shared/AttachmentThumbnail';
import { type ConversationMessage } from 'src/pages/dashboard/Conversations/types';
import { isGifAttachment } from 'src/pages/dashboard/Conversations/utils';

type MessageProps = {
  selectedIndex: number;
  pinnedMessages: ConversationMessage[];
};

const Message: FC<MessageProps> = ({ selectedIndex, pinnedMessages }) => {
  const selectedMessage = pinnedMessages[selectedIndex];
  const hasAttachments = !!selectedMessage.attachments?.length;

  return (
    <Stack
      sx={{
        flex: 1,
        minWidth: 0,
        flexDirection: 'row',
        alignItems: 'center',
        gap: 1,
      }}
    >
      {pinnedMessages.length > 1 && (
        <Stack sx={{ alignSelf: 'stretch', gap: 0.5, py: 0.5 }}>
          {pinnedMessages.map((message, index) => (
            <Stack
              key={message.hu_data.message_ts}
              sx={{
                width: '2px',
                flex: 1,
                borderRadius: 1,
                bgcolor: ({ palette }) =>
                  index === selectedIndex
                    ? palette.new.action.button.background.primary.default
                    : palette.new.border.neutral.default,
              }}
            />
          ))}
        </Stack>
      )}
      <HuAvatar
        Icon={IconPinned}
        alt="Pinned message"
      />

      {hasAttachments && (
        <>
          <AttachmentDescription
            attachments={selectedMessage.attachments || []}
            text={selectedMessage.text}
            highlightedSpans={selectedMessage.hu_data.highlighted_spans}
            isPinned
            fontWeight="fontWeightSemiBold"
          />
          {selectedMessage.attachments?.length === 1 &&
            selectedMessage.attachments[0] &&
            !isGifAttachment(selectedMessage.attachments[0]) && (
              <AttachmentThumbnail
                attachment={selectedMessage.attachments[0]}
                width={40}
                height={40}
              />
            )}
        </>
      )}
      {!hasAttachments && (
        <TypographyTagAndLinkSensitive
          disableLink
          noWrap
          highlightedSpans={selectedMessage.hu_data.highlighted_spans}
          component="span"
        >
          {selectedMessage.text}
        </TypographyTagAndLinkSensitive>
      )}
    </Stack>
  );
};

export default Message;
