import { useCallback, useEffect, useState } from "react";
import { Scrollbars } from "react-custom-scrollbars-2";
import { useInterval } from "ahooks";
import { useLocation } from "react-router-dom";
import styles from "./index.module.less";

let index = 0;

function TextInfoPanel({ content }) {
  const location = useLocation();
  const showNumberPerTimes = 1;

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

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

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

  useInterval(showContent, delay);

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

  return (
    <div className={styles.textInfoPanel} onDoubleClick={stopHandler}>
      <Scrollbars
        className="scrollbars"
        renderThumbVertical={(styles) => {
          return <div className="thumbVertical" {...styles}></div>;
        }}
        renderView={(props) => {
          return <div className="view" {...props}></div>;
        }}
      >
        {contentText}
      </Scrollbars>
    </div>
  );
}

export default TextInfoPanel;
