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

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

import {
  FLOATING_MESSAGE_COLLAPSED_LINES,
  FLOATING_MESSAGE_EXPANDED_MAX_HEIGHT,
  FLOATING_MESSAGE_LONG_TEXT_THRESHOLD,
  FLOATING_MESSAGE_MAX_WIDTH,
} from 'src/pages/dashboard/Conversations/constants';
import { type HighlightedSpan } from 'src/pages/dashboard/Conversations/types';

import TypographyTagAndLinkSensitive from '../../ConversationsThread/ConversationMessage/TypographyTagAndLinkSensitive';

type FloatingMessageProps = {
  text?: string;
  highlightedSpans?: HighlightedSpan[];
  visible?: boolean;
};

const FloatingMessage: FC<FloatingMessageProps> = ({
  text,
  highlightedSpans,
  visible = false,
}) => {
  const [expanded, setExpanded] = useState(false);
  const isLong = (text?.length ?? 0) > FLOATING_MESSAGE_LONG_TEXT_THRESHOLD;

  if (!text) return null;

  return (
    <Stack
      onClick={() => isLong && setExpanded(prev => !prev)}
      sx={{
        backgroundColor: theme => alpha(theme.palette.common.white, 0.5),
        borderRadius: theme => theme.shape.borderRadiusM,
        p: 1,
        mx: 3,
        maxWidth: FLOATING_MESSAGE_MAX_WIDTH,
        cursor: isLong ? 'pointer' : 'default',
        overflow: 'hidden',
        opacity: visible ? 1 : 0,
        transition: 'opacity 0.2s ease',
        pointerEvents: visible ? 'auto' : 'none',
        position: 'absolute',
        bottom: '100%',
        right: 0,
      }}
    >
      <Stack
        sx={{
          ...(expanded && {
            overflow: 'auto',
            maxHeight: FLOATING_MESSAGE_EXPANDED_MAX_HEIGHT,
            scrollbarWidth: 'none',
            '&::-webkit-scrollbar': { display: 'none' },
          }),
          ...(!expanded && {
            display: '-webkit-box',
            WebkitLineClamp: FLOATING_MESSAGE_COLLAPSED_LINES,
            WebkitBoxOrient: 'vertical',
            overflow: 'hidden',
          }),
        }}
      >
        <TypographyTagAndLinkSensitive
          variant="globalXS"
          disableLink
          highlightedSpans={highlightedSpans}
        >
          {text}
        </TypographyTagAndLinkSensitive>
      </Stack>
    </Stack>
  );
};

export default FloatingMessage;
