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

import { useCommentEnableDisable } from 'src/hooks/useCommentEnableDisable';
import useRequiredParams from 'src/hooks/useRequiredParams';
import { enableOrDisableCommentsGroupPost } from 'src/services/groups';
import { GroupPost } from 'src/types/groups';

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

import { setGroupFeedListData, setGroupFeedDetailData } from '../queries';

export type GroupPostCommentEnableOrDisableProps = Omit<MenuItemProps, 'id'> & {
  id: number;
  commentsEnabled: boolean;
};

const GroupPostCommentEnableOrDisable = ({
  id,
  commentsEnabled,
  ...menuProps
}: GroupPostCommentEnableOrDisableProps) => {
  const { id: groupId } = useRequiredParams(['id']);

  const { handleDisableComment, handleEnableComment } = useCommentEnableDisable(
    {
      id,
      enableService: (postId: number, enabled: boolean) =>
        enableOrDisableCommentsGroupPost(groupId, postId, enabled),
      onSuccess: (enabled: boolean) => {
        const updateFn = (oldPost?: GroupPost) => {
          if (oldPost) {
            oldPost.commentsEnabled = enabled;
          }
          return oldPost;
        };
        setGroupFeedListData(id, groupId, updateFn);
        setGroupFeedDetailData(id, groupId, updateFn);
      },
    },
  );

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

export default GroupPostCommentEnableOrDisable;
