import { useCallback, useRef } from 'react';
import { useInView } from 'react-intersection-observer';

import { type LegendListRef } from '@legendapp/list/react';

const useGetMessagesEndRef = (listRef: React.RefObject<LegendListRef>) => {
  const messagesEndRef = useRef(null);

  const [setMessagesEndRef, inViewMessagesEnd] = useInView({
    initialInView: true,
  });

  const setRef = useCallback((node: any) => {
    messagesEndRef.current = node;

    setMessagesEndRef(node);
  }, []);

  const scrollToBottom = useCallback(
    () => listRef.current?.scrollToEnd(),
    [listRef],
  );

  return { scrollToBottom, setRef, inViewMessagesEnd };
};

export default useGetMessagesEndRef;
