import { useCallback, useEffect, useState } from "react";
import { Scrollbars } from "react-custom-scrollbars-2";
import { useInterval } from "ahooks";
import { useLocation } from "react-router-dom";

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="text-info-panel" onDoubleClick={stopHandler}>
      <Scrollbars autoHide autoHideTimeout={1000} autoHideDuration={400}>
        {contentText}
      </Scrollbars>
    </div>
  );
}

export default TextInfoPanel;
