/* eslint-disable react-hooks/exhaustive-deps */
import React, { FC, memo, useEffect, useRef } from 'react';
import { Platform, TextInput, TextStyle } from 'react-native';
import { Colors } from '../Consts';
import { useScaleSize } from '../Text';

export interface TextTypingProps {
  data: string[];
  timeDelayEnd?: number;
  timeDelayNextChar?: number;
  inputStyle?: TextStyle;
}

const TextTyping: FC<TextTypingProps> = ({
  data = [],
  timeDelayEnd = 2000,
  timeDelayNextChar = 20,
  inputStyle = {},
}) => {
  const textRef = useRef<TextInput>(null);
  const scaledFontSize = useScaleSize(12);

  const currentIndex = useRef<number>(0);
  const currentCharIndex = useRef<number>(0);
  const currentText = useRef('');

  const playAnimation = () => {
    const handleResetList = () => {
      currentIndex.current = 0;
      handleAnimation();
    };

    const handleAnimation = () => {
      const listChar = data?.[currentIndex.current]?.split('') || [];
      listChar.length !== 0 && showChar(listChar?.[currentCharIndex.current]);
    };

    currentIndex.current >= data?.length
      ? handleResetList()
      : handleAnimation();
  };

  const showChar = (char?: string) => {
    const handleResetString = () => {
      setTimeout(() => {
        reset();
      }, timeDelayEnd);
    };

    const handleShowChar = () => {
      setTimeout(() => {
        textRef.current?.setNativeProps?.({
          text: currentText.current + char,
        });
        currentText.current += char;
        currentCharIndex.current++;
        playAnimation();
      }, timeDelayNextChar);
    };

    currentCharIndex.current >= (data?.[currentIndex.current]?.length || 0)
      ? handleResetString()
      : handleShowChar();
  };

  const reset = () => {
    const handleNextString = () => {
      currentIndex.current++;
      playAnimation();
    };

    const handleReset = () => {
      setTimeout(() => {
        textRef.current?.setNativeProps?.({
          text: currentText.current.slice(0, -1),
        });
        currentText.current = currentText.current.slice(0, -1);
        currentCharIndex.current--;
        reset();
      }, timeDelayNextChar);
    };

    currentCharIndex.current <= 0 ? handleNextString() : handleReset();
  };

  useEffect(() => {
    setTimeout(() => {
      playAnimation();
    }, 1000);
  }, []);

  return (
    <TextInput
      style={[
        {
          color: Colors.black_12,
          fontSize: scaledFontSize,
          height: Platform.select({
            android: 60,
            ios: 36,
          }),
        },
        inputStyle,
      ]}
      ref={textRef}
      editable={false}
      autoCorrect={false}
      pointerEvents={'none'}
      numberOfLines={1}
      allowFontScaling={false}
    />
  );
};

export default memo(TextTyping);
