import { RefObject, useCallback, useEffect, useRef, useState } from 'react';
import { FlatList, Keyboard } from 'react-native';

const MIN_MESSAGE_HEIGHT = 50;
const DEFAULT_SCROLL_TO_END_DELAY = 500;

export function useAutoScroll({ ref }: { ref: RefObject<FlatList> }) {
  const [currentContentHeight, setCurrentContentHeight] = useState(0);
  const userScrolled = useRef(false);

  const scrollToEnd = useCallback(
    ({ delay }: { delay: number }) => {
      if (ref.current && !userScrolled.current) {
        setTimeout(() => {
          ref.current?.scrollToEnd();
        }, delay);
      }
    },
    [ref, userScrolled.current]
  );

  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => {
        scrollToEnd({ delay: DEFAULT_SCROLL_TO_END_DELAY });
      }
    );
    return () => {
      keyboardDidShowListener.remove();
    };
  }, [scrollToEnd, userScrolled.current]);

  const onScrollEndDrag = useCallback(() => {
    if (!userScrolled.current) {
      userScrolled.current = true;
    }
  }, [userScrolled.current]);

  const onContentSizeChangeHandler = (width: number, height: number) => {
    if (
      height - currentContentHeight > MIN_MESSAGE_HEIGHT &&
      !userScrolled.current
    ) {
      scrollToEnd({ delay: DEFAULT_SCROLL_TO_END_DELAY });
    }
    setCurrentContentHeight(height);
  };

  return { onScrollEndDrag, onContentSizeChangeHandler };
}
