import React, { useEffect } from "react";
import { TextAnimationContainer, Word } from "./styled";
import { findLastIndex } from "lodash-es";

const textList = ["高-效-总-结", "轻-松-学-习", "话-题-分-析", "服-务-洞-察"];
const texts = textList;
const wordsArray = texts.map(text => text.split("-"));
const wordMaxLength = Math.max(...wordsArray.map(wordArray => wordArray.length));
wordsArray.forEach(wordArray => {
  const lengthDiff = wordMaxLength - wordArray.length;
  if (lengthDiff > 0) {
    wordArray.push(...Array(lengthDiff).fill(""));
  }
});

export const TextAnimation = () => {
  const [index, setIndexState] = React.useState(0);
  const indexRef = React.useRef(index);
  const [isPageHidden, setPageHidden] = React.useState(false);

  const firstLineRef = React.useRef<HTMLDivElement>(null);
  const secondLineRef = React.useRef<HTMLDivElement>(null);

  const setIndex = (v: number) => {
    indexRef.current = v;
    setIndexState(v);
  };

  const getNextIndex = () => {
    let firstLineNextIndex = indexRef.current + 1;
    let secondLineNextIndex = firstLineNextIndex + 1;
    if (firstLineNextIndex === wordsArray.length) {
      firstLineNextIndex = 0;
      secondLineNextIndex = 1;
    } else if (firstLineNextIndex === wordsArray.length - 1) {
      secondLineNextIndex = 0;
    }

    return [firstLineNextIndex, secondLineNextIndex];
  };

  const changeWords = () => {
    if (firstLineRef.current && secondLineRef.current) {
      const [firstLineNextIndex, secondLineNextIndex] = getNextIndex();

      const firstLineWords = firstLineRef.current.childNodes;
      const secondLineWords = secondLineRef.current.childNodes;

      firstLineWords.forEach((word, i) => {
        (word as HTMLDivElement).className = "";
        (word as HTMLDivElement).innerText = wordsArray[firstLineNextIndex][i];
      });

      secondLineWords.forEach((word, i) => {
        (word as HTMLDivElement).className = "";
        (word as HTMLDivElement).innerText = wordsArray[secondLineNextIndex][i];
      });

      setIndex(firstLineNextIndex);
    }
  };

  const getOnFirstLineWordAnimationEnd = (
    wordIndex: number
    // isLastWord: boolean,
  ) => {
    return () => {
      if (firstLineRef.current) {
        const firstLineWords = firstLineRef.current.childNodes;
        const word = firstLineWords[wordIndex] as HTMLDivElement;

        word.style.opacity = "0";
      }
    };
  };

  const getOnSecondLineWordAnimationEnd = (wordIndex: number, isLastWord: boolean) => {
    return () => {
      const [firstLineNextIndex] = getNextIndex();

      if (firstLineRef.current && secondLineRef.current) {
        const firstLineWords = firstLineRef.current.childNodes;
        // const secondLineWords = secondLineRef.current.childNodes;

        (firstLineWords[wordIndex] as HTMLDivElement).style.opacity = "1";
        (firstLineWords[wordIndex] as HTMLDivElement).innerText =
          wordsArray[firstLineNextIndex][wordIndex];

        // if (wordsArray[secondLineNextIndex][wordIndex]) {
        //   (secondLineWords[wordIndex] as HTMLDivElement).innerText =
        //     wordsArray[secondLineNextIndex][wordIndex];
        // }
      }

      if (isLastWord) {
        changeWords();
      }
    };
  };

  useEffect(() => {
    const onVisibilityChange = () => {
      if (!firstLineRef.current || !secondLineRef.current) return;

      const firstLineWords = firstLineRef.current.childNodes;
      const secondLineWords = secondLineRef.current.childNodes;
      firstLineWords.forEach((word, i) => {
        (word as HTMLDivElement).style.opacity = "1";
        (word as HTMLDivElement).innerText = wordsArray[indexRef.current][i];
      });
      secondLineWords.forEach((word, i) => {
        (word as HTMLDivElement).innerText =
          wordsArray[indexRef.current + 1 === wordsArray.length ? 0 : indexRef.current + 1][i];
      });
      setPageHidden(document.hidden);
    };

    document.addEventListener("visibilitychange", onVisibilityChange);
    return () => {
      document.removeEventListener("visibilitychange", onVisibilityChange);
    };
  }, []);

  return (
    <TextAnimationContainer>
      <div className={"animation-texts"}>
        <div ref={firstLineRef}>
          {wordsArray[index].map((word, i) => (
            <Word
              key={word + i}
              wordIndex={i}
              onAnimationEnd={getOnFirstLineWordAnimationEnd(i)}
              style={isPageHidden ? { animation: "none" } : undefined}
            >
              {word}
            </Word>
          ))}
        </div>

        <div ref={secondLineRef}>
          {wordsArray[index + 1 === wordsArray.length ? 0 : index + 1].map((word, i, text) => (
            <Word
              key={word + i}
              wordIndex={i}
              isSecondLine
              onAnimationEnd={getOnSecondLineWordAnimationEnd(
                i,
                i === findLastIndex(text, w => !!w)
              )}
              style={isPageHidden ? { animation: "none" } : undefined}
            >
              {word}
            </Word>
          ))}
        </div>
      </div>
    </TextAnimationContainer>
  );
};
