import React, {useCallback, useEffect, useMemo} from 'react';
import {useQuery} from 'react-query';
import {useBackHandler} from '@hooks/useBackHandler';
import {useGoBack} from '@hooks/useGoBack';
import {postQueryKeys} from '@modules/post/constants';
import {getMarketplacePost} from '@modules/marketplace/services';
import {updateFeedPost} from '@modules/post/utils';
import {Post} from '@modules/post/interfaces';
import {
  usePostById,
  useFeedActions,
  useFeedLoadingStates,
} from '@modules/post/store/useFeedStore';
import {usePermissions} from '@redux/selectors';

import PostDetailWithComments from '../PostDetailWithComments';

interface Props {
  id: number;
  shouldScrollToComments?: boolean;
  autoFocus?: boolean;
  isMarketplace?: boolean;
  onOptionsPress?: () => void;
  withOptions?: boolean;
}

function PostDetailScreen({
  id: postId,
  shouldScrollToComments,
  autoFocus,
  isMarketplace,
  onOptionsPress,
  withOptions,
}: Props) {
  const {goBack} = useGoBack();
  const {
    MANAGE_COMMENTS: canManageCommentsGeneral,
    MANAGE_FEED_COMMENTS: canManageCommentsFeed,
    CREATE_COMMENT: canCommentGeneral,
    CREATE_COMMENT_IN_POSTS: canCommentInPosts,
    VIEW_POSTS: canViewPosts,
    MANAGE_POSTS: canManagePosts,
    REQUEST_FEED_POST_APPROVAL: requestFeedPostApproval,
    CAN_APPROVE_FEED_POSTS: canApproveFeedPosts,
  } = usePermissions();

  const canManageComments = canManageCommentsGeneral || canManageCommentsFeed;
  const canComment = canCommentGeneral || canCommentInPosts;

  const onGoBack = useCallback(() => {
    goBack();
    return true;
  }, [goBack]);

  useBackHandler(onGoBack);

  const feedPost = usePostById(postId);
  const {fetchPostDetail} = useFeedActions();
  const {isLoadingPostDetail} = useFeedLoadingStates();

  const postEnabled = useMemo(
    () => !!postId && canViewPosts && !!isMarketplace,
    [postId, canViewPosts, isMarketplace],
  );

  useEffect(() => {
    // For marketplace posts, check if query is enabled and should navigate back
    if (isMarketplace && !postEnabled) {
      goBack();
      return;
    }

    // For non-marketplace posts, check if we have permissions and post exists
    if (!isMarketplace && (!canViewPosts || !postId)) {
      goBack();
    }
  }, [goBack, postEnabled, isMarketplace, canViewPosts, postId]);

  // Fetch post detail for non-marketplace posts
  useEffect(() => {
    if (!isMarketplace && postId && canViewPosts) {
      fetchPostDetail(postId).catch(goBack);
    }
  }, [isMarketplace, postId, canViewPosts, fetchPostDetail, goBack]);

  // Create refetch function for non-marketplace posts
  const refetchFeedPost = useCallback(() => {
    if (!isMarketplace && postId) {
      fetchPostDetail(postId);
    }
  }, [isMarketplace, postId, fetchPostDetail]);

  const {
    data: post,
    isFetching: isLoadingPost,
    refetch,
  } = useQuery(postQueryKeys.post(postId), () => getMarketplacePost(postId), {
    enabled: postEnabled,
    onError: goBack,
    onSuccess: (fetchedPost: Post) =>
      fetchedPost && updateFeedPost(fetchedPost.id, () => fetchedPost),
  });

  return (
    <PostDetailWithComments
      postId={postId}
      shouldScrollToComments={shouldScrollToComments}
      autoFocus={autoFocus}
      post={isMarketplace ? post : feedPost}
      onOptionsPress={onOptionsPress}
      withOptions={withOptions}
      isLoadingPost={isMarketplace ? isLoadingPost : isLoadingPostDetail}
      refetchPost={isMarketplace ? refetch : refetchFeedPost}
      canManageComments={canManageComments}
      canComment={canComment}
      canManagePosts={canManagePosts}
      canApproveFeedPosts={canApproveFeedPosts}
      requestFeedPostApproval={requestFeedPostApproval}
      canViewPosts={canViewPosts}
    />
  );
}

export default PostDetailScreen;
