import { useCallback, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { Scrollbars } from "react-custom-scrollbars-2";
import { useInterval } from "ahooks";

let index = 0;
function TextInfoPanel({ title, content }) {
  const showNumberPerTimes = 1;
  const { toolbar } = useSelector((state) => state.data);

  const [delay, setDelay] = useState(80);
  const [contentText, setContentText] = useState("");

  useEffect(() => {
    index = 0;
  }, [toolbar]);

  const showContent = useCallback(() => {
    const isFinished = contentText.length >= content.length;
    if (!isFinished) {
      setContentText((text) => {
        index += showNumberPerTimes;
        return text + content[index - 1];
      });
    } else setDelay(undefined);
  }, [contentText]);

  useInterval(showContent, delay);

  const stopHandler = useCallback(() => {
    setDelay(undefined);
    index = 0;
    setContentText(content);
  }, []);

  return (
    <div className="textInfoPanel" onDoubleClick={stopHandler}>
      <div className="title" title={title}>
        {title}
      </div>
      <div className="content">
        <Scrollbars autoHide autoHideTimeout={1000} autoHideDuration={400}>
          {contentText}
        </Scrollbars>
      </div>
    </div>
  );
}

export default TextInfoPanel;
