import { Fragment } from 'react';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';

import { useAuth } from 'src/contexts/JWTContext';
import { buildCommentDraftKey } from 'src/utils/composerDrafts';

import ChildCommentList from 'src/components/comments/ChildCommentList';
import Comment from 'src/components/comments/Comment';
import CommentAdd from 'src/components/comments/CommentAdd';
import { type CommentItemProps } from 'src/components/comments/types';
import { usePost } from 'src/components/post/PostContext';

export const CommentItem = (props: CommentItemProps) => {
  const {
    comment,
    handlers,
    reply,
    postId,
    maxAttachmentsBytes,
    context,
    replyCommentMutation,
    isReplyFocused,
    canManageComments,
    canReact,
    isGroupArchived,
    userIsMember,
    isGroupAdmin,
    handleReplyBlur,
    handleDeleteUserReply,
  } = props;

  const childCommentsQueryConfig =
    handlers.getChildCommentsQueryConfig(comment);

  const isGroupContext = context === 'groups';
  const { groupId } = usePost();
  const { user: loggedUser } = useAuth();
  const isDraftSupportedContext = context === 'feed' || context === 'groups';
  const draftScope =
    isGroupContext || groupId !== undefined ? 'groups' : 'feed';
  const replyDraftKey =
    isDraftSupportedContext && loggedUser
      ? buildCommentDraftKey({
          scope: draftScope,
          postId,
          userId: loggedUser.id,
          parentId: comment.id,
          groupId,
        })
      : null;

  const commonProps = {
    context,
    postId,
    maxAttachmentsBytes,
    handlers,
    reply,
    canManageComments,
    canReact,
    isGroupArchived,
    userIsMember,
    isGroupAdmin,
  };

  return (
    <Fragment>
      <Comment
        comment={comment}
        onDelete={handlers.handleDeleteSuccess}
        onEdit={handlers.handleEditSuccess}
        onReply={handlers.handleReply}
        onRemoveReaction={handlers.handleRemoveReactionSuccess}
        onAddReaction={handlers.handleAddReactionSuccess}
        {...commonProps}
      />

      <ChildCommentList
        childrenNumber={comment.childrenNumber ?? 0}
        onDelete={handlers.handleDeleteSuccess}
        onEdit={handlers.handleEditSuccess}
        onReply={handlers.handleReplyChild}
        commentChildren={comment.children ?? []}
        onRemoveReaction={handlers.handleRemoveReactionSuccess}
        onAddReaction={handlers.handleAddReactionSuccess}
        queryConfig={childCommentsQueryConfig}
        {...commonProps}
      />

      {reply &&
        reply.id === comment?.id &&
        (!isGroupContext || !isGroupArchived) && (
          <>
            {replyCommentMutation?.isLoading && (
              <Box sx={{ textAlign: 'center', mt: 1 }}>
                <CircularProgress />
              </Box>
            )}
            <Box sx={{ ml: 1 }}>
              <CommentAdd
                id={comment.id}
                onSubmit={handlers.handleReplyComment}
                maxAttachmentsBytes={maxAttachmentsBytes}
                isCommentReply={true}
                replyUser={reply?.user}
                onDeleteUserReply={handleDeleteUserReply}
                setInitialFocus={isReplyFocused}
                onBlur={handleReplyBlur}
                isNewTheme={isGroupContext}
                draftKey={replyDraftKey}
              />
            </Box>
          </>
        )}
    </Fragment>
  );
};
