import { useContext, MutableRefObject } from 'react';

import {
  ScrollToMessageContext,
  ScrollToMessageContextValue,
} from 'src/contexts/ScrollToMessageContext';
import { addAnimation } from 'src/utils/styles';

export type ScrollToMessageObject = ScrollToMessageContextValue & {
  scrollToMessage: () => Promise<void>;
};

export const useScrollToMessage = (
  fetchNextPage?: Function,
  ref?: MutableRefObject<any>,
): ScrollToMessageObject => {
  const { messageToScrollTo, clearScrollTo, ...context } =
    useContext<ScrollToMessageContextValue>(ScrollToMessageContext);

  const scrollToMessage = async () => {
    if (ref.current) {
      ref.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
      addAnimation(ref.current.children[1], 'flash-animation');
      clearScrollTo();
    } else {
      fetchNextPage && (await fetchNextPage());
    }
  };

  return {
    scrollToMessage,
    messageToScrollTo,
    clearScrollTo,
    ...context,
  };
};

export default useScrollToMessage;
