import { useEffect, useRef } from 'react';

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

import { useReplyMessageValue } from '../contexts/ReplayMessageConversationContext';

const useManageScrollConversations = (
  listRef: React.RefObject<LegendListRef>,
) => {
  const unreadMessageRef = useRef<HTMLDivElement>(null);
  const { messageToReply } = useReplyMessageValue();

  useEffect(() => {
    const ref = listRef.current;

    if (!ref) {
      return;
    }

    const scrollState = ref.getState?.();

    if (!scrollState) {
      return;
    }

    const isScrolledToBottom = scrollState.isAtEnd;

    if (messageToReply?.ts) {
      if (isScrolledToBottom) {
        setTimeout(() => {
          ref?.scrollToEnd();
        }, 16);
        return;
      }
    }
  }, [messageToReply?.ts]);

  return { listRef, unreadMessageRef };
};

export default useManageScrollConversations;
