import React, { useEffect, useRef, useState } from "react";
import {
  MultiEllipsisContainer,
  Content,
  ExpendButton,
  ExpendText,
  EllipsisText,
  RedDot,
} from "./styled";

interface MultiEllipsisProps extends React.HTMLAttributes<HTMLDivElement> {
  text: string;
  lineClamp?: number;
  showRedDot?: boolean;
  showExpend?: boolean;
  onExpand?: (v: boolean) => void;
}

// eslint-disable-next-line max-lines-per-function
export const MultiEllipsis = (props: MultiEllipsisProps) => {
  const { text, lineClamp, showRedDot, showExpend = true, onExpand, ...rest } = props;
  const [rows, setRows] = useState(0);
  const [expand, setExpand] = useState(false);
  const [ellipsisVisible, setEllipsisVisible] = useState(true);
  const [expandHeight, setExpandHeight] = useState("auto");
  const [lineHeight, setLineHeight] = useState(24);
  const textRef = useRef<HTMLDivElement>(null);
  const maxExpandHeight = useRef(0);
  // const expandHeightRef = useRef(0);

  const expandText = () => {
    setExpand(preExpand => {
      if (preExpand) {
        setEllipsisVisible(false);
      }
      onExpand?.(!preExpand);
      return !preExpand;
    });
  };

  useEffect(() => {
    if (!window.ResizeObserver || !textRef.current) return;

    const observer = new ResizeObserver(() => {
      if (!textRef.current) return;

      const { lineHeight: lineHeightString } = window.getComputedStyle(textRef.current);
      const lineHeightNumber = Number(lineHeightString.split("px")[0] || "24");
      const { height } = textRef.current.getBoundingClientRect();

      setLineHeight(lineHeightNumber);
      if (lineClamp && lineHeightNumber * lineClamp < height) {
        setRows(lineClamp);
      } else {
        setRows(0);
      }
      if (expand) {
        maxExpandHeight.current = Math.max(maxExpandHeight.current, height);
        // if (maxExpandHeight.current > 0 && maxExpandHeight.current !== height && expandHeightRef.current === height) {
        if (maxExpandHeight.current > 0 && maxExpandHeight.current !== height) {
          // expandHeightRef.current = maxExpandHeight.current;
          setExpandHeight(`${maxExpandHeight.current}px`);
          maxExpandHeight.current = 0;
          return;
        }
      }
      // expandHeightRef.current = height;
      setExpandHeight(`${height}px`);
    });

    observer.observe(textRef.current);
    return () => {
      observer.disconnect();
    };
  }, [lineClamp, setExpandHeight, expand, expandHeight, text]);

  return (
    <MultiEllipsisContainer {...rest}>
      <Content
        className={"multiEllipsis-content"}
        expand={expand}
        expandHeight={expandHeight}
        lineHeight={lineHeight}
        rows={rows}
        onTransitionEnd={() => setEllipsisVisible(true)}
      >
        {!!rows && (
          <ExpendButton>
            <EllipsisText
              style={{
                display: expand ? "none" : "inline",
                opacity: ellipsisVisible ? "1" : "0",
              }}
            >
              {"..."}
            </EllipsisText>
            {showExpend && (
              <ExpendText onClick={expandText}>{expand ? "收起" : "展开全部"}</ExpendText>
            )}
          </ExpendButton>
        )}
        <div ref={textRef} className={"multiEllipsis-text"}>
          {text}
        </div>
      </Content>
      {showRedDot && rows > 0 && !expand && <RedDot rows={rows} lineHeight={lineHeight} />}
    </MultiEllipsisContainer>
  );
};
