import { MenuItemProps } from '@material-hu/components/design-system/Menu/components/MenuItem/types';

import { useCommentEnableDisable } from 'src/hooks/useCommentEnableDisable';
import { editPost } from 'src/services/events';
import { EventPostType } from 'src/types/events';

import CommentEnableOrDisableMenuItem from 'src/components/comments/CommentEnableOrDisableMenuItem';

import { setEventPostData } from '../queries';

export type EventPostCommentEnableOrDisableProps = Omit<MenuItemProps, 'id'> & {
  post: EventPostType;
  eventId: number;
};

const EventPostCommentEnableOrDisable = ({
  post,
  eventId,
  ...menuProps
}: EventPostCommentEnableOrDisableProps) => {
  const { handleDisableComment, handleEnableComment } = useCommentEnableDisable(
    {
      id: post.id,
      enableService: (id: number, enabled: boolean) =>
        editPost(eventId, id, { body: post.body, commentsEnabled: enabled }),
      onSuccess: (enabled: boolean) => {
        const updateFn = (oldPost?: EventPostType) => {
          if (oldPost) {
            oldPost.commentsEnabled = enabled;
          }
          return oldPost;
        };
        setEventPostData(eventId, post.id, updateFn);
      },
    },
  );

  return (
    <CommentEnableOrDisableMenuItem
      {...menuProps}
      commentsEnabled={post.commentsEnabled ?? true}
      onDisableComment={handleDisableComment}
      onEnableComment={handleEnableComment}
    />
  );
};

export default EventPostCommentEnableOrDisable;
