import React, {memo, useCallback, useState} from 'react';
import {View} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {
  BasePost,
  Post,
  Typography,
  PostFooter,
  PostOptions,
  PostTitle,
  KeyUpdateLabel,
} from '@components';
import {Attachment} from '@interfaces/attachments';
import {usePostById, usePostIsPinned} from '@modules/post/store/useFeedStore';
import PostCommentItem from '@modules/post/components/PostDetailComment';
import useReactToPost from '@modules/post/hooks/useReactToPost';
import {Post as PostType} from '@modules/post/interfaces';
import {getPost} from '@modules/post/services';
import {useUserId} from '@redux/selectors';
import {Screens} from '@shared/constants';
import {ScreenKey} from '@shared/stores/useActivePostsStore';
import {getExactTimeAgo, wait} from '@shared/utils';
import {useTheme} from '@shared/theme';
import {useCommunityFeature} from '@stores/communityFeatures';

import {styles} from './styles';

function FeedPostItem({
  postId,
  canManagePosts = false,
  canManageComments = false,
  onPostPress: onPostPressProp,
  onOptionsPress,
  withOptions = true,
  withFooter = true,
  showLastComment = true,
  isPreviewPost = false,
  alwaysShowGroupPosts = false,
  screenKey,
}: {
  postId: number;
  canManagePosts?: boolean;
  canManageComments?: boolean;
  onPostPress?: () => void;
  onOptionsPress?: () => void;
  withOptions?: boolean;
  withFooter?: boolean;
  showLastComment?: boolean;
  isPreviewPost?: boolean;
  alwaysShowGroupPosts?: boolean;
  screenKey?: Nullable<ScreenKey>;
}) {
  const navigation = useNavigation();
  const {theme} = useTheme();
  const post = usePostById(postId);
  const isPostPinned = usePostIsPinned(postId);
  const groupId = post?.group?.id;
  const {togglePostReaction} = useReactToPost();
  const canViewGroupPostsInFeed = useCommunityFeature(
    'VIEW_GROUP_POSTS_IN_FEED',
  );
  const [isPostOptionsVisible, setIsPostOptionsVisible] = useState(false);
  const userId = useUserId();
  const isOwner = userId === post?.user.id;
  const isGroupPostInFeed = !!post?.group;

  const handlePostPress = useCallback(
    (autoFocus: boolean) => {
      if (onPostPressProp) {
        onPostPressProp();
      } else if (groupId) {
        navigation.navigate(Screens.GROUP_POST_DETAIL, {
          id: post.id,
          groupId,
          autoFocus,
        });
      } else {
        navigation.navigate(Screens.POST_DETAIL, {id: post.id, autoFocus});
      }
    },
    [navigation, groupId, post?.id, onPostPressProp],
  );

  const onPressPost = () => {
    handlePostPress(false);
  };

  const onPressComment = () => {
    handlePostPress(true);
  };

  const onReactionPress = (postToUpdate: PostType) => (reaction: string) => {
    togglePostReaction({
      post: postToUpdate,
      reaction,
    });
  };

  const navigateToEditScreen = useCallback(async () => {
    if (!post) return;
    const completePost = await getPost(post.id);
    await wait(200);
    if (completePost) {
      const postToEdit = completePost.attachments?.some(
        a => typeof (a as Attachment).position !== 'number',
      )
        ? {
            ...completePost,
            attachments: completePost.attachments.map((item, position) => ({
              ...item,
              position,
            })),
          }
        : completePost;
      navigation.navigate(Screens.PUBLISH_POST, {post: postToEdit as PostType});
    }
  }, [navigation, post]);

  const renderDescription = useCallback(
    () =>
      post ? (
        <View style={styles.timeAgoContainer}>
          <Typography
            variant="xxs"
            color={theme.text.neutral.lighter}
            numberOfLines={1}
            adjustsFontSizeToFit>
            {getExactTimeAgo(post.publicationDatetime || post.createdAt)}
          </Typography>
          {post.isKeyUpdate && <KeyUpdateLabel />}
        </View>
      ) : null,
    [post, theme.text.neutral.lighter],
  );

  const handleOptionsPress = useCallback(() => {
    setIsPostOptionsVisible(true);
  }, [setIsPostOptionsVisible]);

  if (!post || (!canViewGroupPostsInFeed && groupId && !alwaysShowGroupPosts))
    return null;

  return (
    <>
      <Post
        style={styles.post}
        onPressOptions={onOptionsPress || handleOptionsPress}
        onPressPost={onPressPost}
        withOptions={withOptions}
        post={post as BasePost}
        renderDescription={renderDescription}
        screenKey={screenKey}
        TitleComponent={<PostTitle post={post} />}
        isPreviewPost={isPreviewPost}
        isGroupPostInFeed={isGroupPostInFeed}
        isInsightsQuickLinkEnabled
        canInteract
        canManagePosts={canManagePosts}
        truncate>
        <View>
          {withFooter && (
            <PostFooter
              post={post}
              groupId={groupId}
              canInteract
              onReactionPress={onReactionPress(post)}
              onPressComment={onPressComment}
            />
          )}
          {!isPreviewPost && showLastComment && !!post.lastComments?.length && (
            <View style={styles.commentContainer}>
              <PostCommentItem
                showOptions={false}
                commentId={post.lastComments[0].id}
                comment={post.lastComments[0]}
                canManagePosts={canManagePosts}
                canManageComments={canManageComments}
                postId={postId}
                groupId={groupId}
              />
            </View>
          )}
        </View>
      </Post>
      {withOptions && !!post && (
        <PostOptions
          isOwner={isOwner}
          isPinned={isPostPinned || post.pinned}
          post={post}
          isGroupPostInFeed={isGroupPostInFeed}
          canEdit
          canManagePosts={canManagePosts}
          navigateToEditScreen={navigateToEditScreen}
          isVisible={isPostOptionsVisible}
          setIsVisible={setIsPostOptionsVisible}
        />
      )}
    </>
  );
}
export default memo(FeedPostItem);
