import React, { memo, useState, useRef } from "react";
import { Tooltip } from "@tingwujs/design";
import { DisplaySpeakerSummary, SpeakerSummaryController } from "../../spheres";
import {
  Wrapper,
  Heading,
  SpeakerName,
  ContentContainer,
  Content,
  DefaultAvatar,
  AvatarContainer,
} from "./styled";

interface SpeakerSummaryItemProps {
  speakerSummaryController: SpeakerSummaryController;
  summary: DisplaySpeakerSummary;
  expanded?: boolean;
  isExpandItem?: boolean;
  contentClassRef: any;
}

export const SpeakerSummaryItem: React.FC<SpeakerSummaryItemProps> = memo(props => {
  const { speakerSummaryController, summary, expanded = false, isExpandItem = false } = props;
  const [showFullName, setShowFullName] = useState(false);
  const nameRef = useRef<HTMLSpanElement | null>(null);

  const speakerName = speakerSummaryController.renderSpeakerName(summary);
  const avatar = speakerSummaryController.renderSpeakerAvatar(summary) || <DefaultAvatar />;

  const onMouseEnter = () => {
    if (nameRef.current) {
      const { clientWidth, scrollWidth } = nameRef.current;
      if (clientWidth < scrollWidth) {
        setShowFullName(true);
      }
    }
  };

  const onMouseLeave = () => {
    setShowFullName(false);
  };

  const content = summary.isTextTooShort ? "发言内容太少了，无总结内容哦" : summary.content;

  React.useEffect(() => {
    if (isExpandItem || expanded) {
      props.contentClassRef.current = "opacityAnimation";
    }
  }, [isExpandItem, expanded]);

  return (
    <Wrapper>
      <Heading>
        <AvatarContainer
          onMouseEnter={isExpandItem ? undefined : onMouseEnter}
          onMouseLeave={isExpandItem ? undefined : onMouseLeave}
        >
          {avatar}
        </AvatarContainer>
        {!isExpandItem && (
          <Tooltip
            title={summary.isDeleted ? "该发言人已被删除" : speakerName}
            placement={"bottomLeft"}
            overlayStyle={{ maxWidth: 260 }}
            visible={showFullName}
            getPopupContainer={triggerNode => triggerNode}
          >
            <SpeakerName ref={nameRef} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
              {speakerName}
            </SpeakerName>
          </Tooltip>
        )}
      </Heading>
      <ContentContainer>
        <Content className={isExpandItem ? props.contentClassRef.current : ""} expanded={expanded}>
          {content}
        </Content>
      </ContentContainer>
    </Wrapper>
  );
});
