import { FC, createContext, useState } from 'react';

import { Message } from 'src/types/chats';

export type ScrollToMessageContextValue = {
  messageToScrollTo: Message;
  setScrollTo: (message: Message) => void;
  clearScrollTo: () => void;
};

export const ScrollToMessageContext =
  createContext<ScrollToMessageContextValue>({
    messageToScrollTo: null,
    setScrollTo: () => null,
    clearScrollTo: () => null,
  });

export const ScrollToMessageProvider: FC<
  React.PropsWithChildren<unknown>
> = props => {
  const { children } = props;

  const [messageToScrollTo, setMessageToScrollTo] = useState<Message | null>(
    null,
  );

  const setScrollTo = (message: Message) => {
    setMessageToScrollTo(message);
  };

  const clearScrollTo = () => {
    setMessageToScrollTo(null);
  };

  return (
    <ScrollToMessageContext.Provider
      value={{
        messageToScrollTo,
        setScrollTo,
        clearScrollTo,
      }}
    >
      {children}
    </ScrollToMessageContext.Provider>
  );
};

export const ScrollToMessageConsumer = ScrollToMessageContext.Consumer;

export default ScrollToMessageContext;
