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 {Post as TPost, PostsData} from '@modules/post/interfaces';
import {usePostById} from '@modules/group/store/useGroupFeedStore';
import useReactToPost from '@modules/group/hooks/useReactToPost';
import GroupComment from '@modules/group/components/GroupComment';
import {useUserId} from '@redux/selectors';
import {Screens} from '@shared/constants';
import {getExactTimeAgo} from '@shared/utils';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  postId: number;
  canManagePosts?: boolean;
  canManageComments?: boolean;
  canInteract?: boolean;
  groupId: number;
  isArchived?: boolean;
  isPreviewPost?: boolean;
  withFooter?: boolean;
}

function GroupPost({
  postId,
  canManagePosts,
  canInteract,
  groupId,
  isArchived,
  isPreviewPost = false,
  withFooter = true,
}: Props) {
  const navigation = useNavigation();
  const {theme} = useTheme();
  const userId = useUserId();
  const post: PostsData | undefined = usePostById(groupId, postId);
  const {togglePostReaction} = useReactToPost({groupId});
  const [isPostOptionsVisible, setIsPostOptionsVisible] = useState(false);
  const isOwner = userId === post?.user.id;
  const handlePostPress = (autoFocus: boolean) => {
    navigation.navigate(Screens.GROUP_POST_DETAIL, {
      id: post?.id,
      groupId,
      autoFocus,
    });
  };

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

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

  const onReactionPress = (postToUpdate: TPost) => (reaction: string) => {
    togglePostReaction({
      postId: postToUpdate.id,
      postReactions: postToUpdate.reactions,
      reaction,
    });
  };

  const renderDescription = useCallback(
    () => (
      <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>
    ),
    [post, theme.text.neutral.lighter],
  );

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

  const navigateToEditScreen = useCallback(() => {
    if (post) {
      const postToEdit = post.attachments?.some(
        a => typeof (a as Attachment).position !== 'number',
      )
        ? {
            ...post,
            attachments: post.attachments.map((item, position) => ({
              ...item,
              position,
            })),
          }
        : post;
      navigation.navigate(Screens.PUBLISH_GROUP_POST, {
        post: postToEdit,
        groupId,
      });
    }
  }, [groupId, navigation, post]);

  if (!post) return null;

  return (
    <>
      <Post
        style={styles.post}
        onPressPost={onPressPost}
        onPressOptions={handleOptionsPress}
        withOptions={!isPreviewPost && !isArchived}
        post={post as BasePost}
        renderDescription={renderDescription}
        canManagePosts={canManagePosts}
        isInsightsQuickLinkEnabled
        canInteract={canInteract}
        groupId={groupId}
        TitleComponent={<PostTitle post={post} />}
        isPreviewPost={isPreviewPost}
        truncate>
        <View>
          {withFooter && (
            <PostFooter
              post={post}
              groupId={groupId}
              groupIsArchived={!!isArchived}
              canInteract={!!canInteract}
              onReactionPress={onReactionPress(post)}
              onPressComment={onPressComment}
            />
          )}
          {!isPreviewPost && !!post.lastComments?.length && (
            <View style={styles.commentContainer}>
              <GroupComment
                showOptions={false}
                commentId={post.lastComments[0].id}
                comment={post.lastComments[0]}
                iAmAdmin={!!canManagePosts}
                canInteract={!!canInteract}
                postId={postId}
                groupId={groupId}
                isArchived={isArchived}
              />
            </View>
          )}
        </View>
      </Post>
      {!isArchived && (
        <PostOptions
          isOwner={isOwner}
          isPinned={post.pinned}
          post={post}
          canEdit
          canManagePosts={canManagePosts}
          navigateToEditScreen={navigateToEditScreen}
          groupId={groupId}
          isVisible={isPostOptionsVisible}
          setIsVisible={setIsPostOptionsVisible}
        />
      )}
    </>
  );
}

export default memo(GroupPost);
