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

export type NewPostNotificationContextValue = {
  hasNewPosts: boolean;
  onAddNewPost: () => void;
  onRemoveNewPosts: () => void;
};

const NewPostNotificationContext =
  createContext<NewPostNotificationContextValue>({
    hasNewPosts: false,
    onAddNewPost: () => null,
    onRemoveNewPosts: () => null,
  });

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

  const [hasNewPosts, setHasNewPosts] = useState(false);

  const onAddNewPost = useCallback(() => {
    setHasNewPosts(true);
  }, []);

  const onRemoveNewPosts = useCallback(() => {
    setHasNewPosts(false);
  }, []);

  return (
    <NewPostNotificationContext.Provider
      value={{ hasNewPosts, onAddNewPost, onRemoveNewPosts }}
    >
      {children}
    </NewPostNotificationContext.Provider>
  );
};

export const useNewPostNotification = () =>
  useContext(NewPostNotificationContext);
