import React, {useCallback} from 'react';
import {StackActions, useNavigation} from '@react-navigation/native';
import {useDispatch} from 'react-redux';
import {Reaction} from '@interfaces/reaction';
import {Comment, CommentableType} from '@interfaces/comments';
import CommentItem from '@modules/post/screens/CommentDetailRefactored/components/CommentItem';
import {openReactionPicker} from '@modules/app/redux';
import {useCommentById} from '@modules/group/store/useGroupPostCommentsStore';
import useReactToComments from '@modules/group/hooks/useReactToComments';
import {Screens} from '@shared/constants';

interface Props {
  postId: number;
  groupId: number;
  parentId?: number;
  commentId: number;
  isReply?: boolean;
  onReplyPress: (comment: Comment) => void;
  userId: number;
  isArchived?: boolean;
}
function GroupCommentItem({
  postId,
  groupId,
  parentId,
  commentId,
  isReply = true,
  onReplyPress,
  userId,
  isArchived,
}: Props) {
  const navigation = useNavigation();
  const dispatch = useDispatch();
  const {toggleCommentReaction} = useReactToComments({groupId});
  const postComment = useCommentById(postId, commentId, parentId);

  const onTagPress = useCallback(
    (targetId: number) => {
      navigation.dispatch(
        StackActions.push(Screens.PROFILE, {userId: targetId}),
      );
    },
    [navigation],
  );

  const onReactionPress = useCallback(
    ({
      reaction,
      commentId: commentIdToReact,
      reactions,
    }: {
      reaction: string;
      commentId: number;
      reactions: Reaction[];
    }) => {
      toggleCommentReaction({
        postId,
        commentId: commentIdToReact,
        parentId,
        reaction,
        reactions: reactions || postComment?.reactions || [],
      });
    },
    [toggleCommentReaction, postId, parentId, postComment?.reactions],
  );

  const onToggleSelectNewReaction = useCallback(
    ({comment}: {comment: Comment}) =>
      dispatch(
        openReactionPicker({
          commentId: comment.id,
          commentableType: CommentableType.POST,
          postId,
          parentId: comment?.id === commentId ? undefined : commentId,
          reactions: comment?.reactions || [],
          onReactionSelected: reaction =>
            toggleCommentReaction({
              postId,
              commentId: comment.id,
              parentId,
              reaction,
              reactions: comment?.reactions || [],
            }),
        }),
      ),
    [dispatch, postId, commentId, toggleCommentReaction, parentId],
  );

  if (!postComment) return null;

  return (
    <CommentItem
      postId={postId}
      groupId={groupId}
      item={postComment}
      isReply={isReply}
      onTagPress={onTagPress}
      onReactionPress={onReactionPress}
      onToggleSelectNewReaction={onToggleSelectNewReaction}
      onReply={onReplyPress}
      isOwner={userId === postComment.user.id}
      isArchived={isArchived}
    />
  );
}

export default GroupCommentItem;
