import {
  PropsWithChildren,
  useRef,
  RefObject,
  createContext,
  useContext,
  useMemo,
} from 'react';

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

interface MessagesListRefMethods {
  scrollToMessageByTs: (ts: string, viewPosition?: number) => void;
  scheduleScrollTo: (action: () => void) => void;
}

const MessagesListRefProviderContext = createContext<{
  listRef: RefObject<Nullable<LegendListRef>>;
  listMethodsRef: RefObject<Nullable<MessagesListRefMethods>>;
}>({
  listRef: {current: null},
  listMethodsRef: {current: null},
});

export function MessagesListRefProvider({children}: PropsWithChildren) {
  const listRef = useRef<Nullable<LegendListRef>>(null);
  const listMethodsRef = useRef<Nullable<MessagesListRefMethods>>(null);

  const values = useMemo(
    () => ({
      listMethodsRef,
      listRef,
    }),
    [listMethodsRef, listRef],
  );

  return (
    <MessagesListRefProviderContext.Provider value={values}>
      {children}
    </MessagesListRefProviderContext.Provider>
  );
}

export const useMessagesListRef = () => {
  return useContext(MessagesListRefProviderContext).listRef;
};

export const useMessagesListMethodsRef = () => {
  return useContext(MessagesListRefProviderContext).listMethodsRef;
};
