import { Tooltip } from '@tingwu/design';
import { memo, useCallback, useMemo, useRef, useState } from 'react';
import { ToDoListItemProps } from '../index.d';
import { ToDoListItemValue } from '../styled';

const ToDoItemTitle = memo(({ value }: ToDoListItemProps) => {
  const [tipsVisible, setTipsVisible] = useState(false);
  const timmerRef = useRef();
  const divChange = useCallback(
    (div) => {
      if (div) {
        timmerRef.current && clearTimeout(timmerRef.current);
        timmerRef.current = setTimeout(() => {
          timmerRef.current = undefined;
          const flag =
            (div.scrollHeight as number) > (div.clientHeight as number);
          setTipsVisible(flag);
        }, 500);
      }
    },
    [setTipsVisible, timmerRef],
  );
  const contentView = useMemo(() => {
    return <ToDoListItemValue ref={divChange}>{value}</ToDoListItemValue>;
  }, [value, divChange, setTipsVisible]);

  if (!tipsVisible) {
    return contentView;
  }
  return (
    <Tooltip
      title={value}
      color="#27264D"
      placement="right"
      overlayInnerStyle={{ maxWidth: 320 }}
    >
      {contentView}
    </Tooltip>
  );
});

export default ToDoItemTitle;
