import React, {useCallback} from 'react';
import {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 {useEventCommentById} from '@modules/events/store/useEventCommentsStore';
import useReactToEventComments from '@modules/events/hooks/useReactToEventComments';
import {Screens} from '@shared/constants';

interface Props {
  eventId: number;
  postId: number;
  parentId?: number;
  commentId: number;
  isReply?: boolean;
  onReplyPress: (comment: Comment) => void;
  userId: number;
}

function EventCommentItem({
  eventId,
  postId,
  parentId,
  commentId,
  isReply = true,
  onReplyPress,
  userId,
}: Props) {
  const navigation = useNavigation();
  const dispatch = useDispatch();
  const {toggleCommentReaction} = useReactToEventComments(eventId);
  const postComment = useEventCommentById({postId, commentId, parentId});

  const onTagPress = useCallback(
    (targetId: number) => {
      navigation.navigate(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}
      item={postComment}
      isReply={isReply}
      onTagPress={onTagPress}
      onReactionPress={onReactionPress}
      onToggleSelectNewReaction={onToggleSelectNewReaction}
      onReply={onReplyPress}
      isOwner={userId === postComment.user.id}
    />
  );
}

export default EventCommentItem;
