import React, { useState } from 'react';
import { Text, Pressable, FlatList, StyleSheet, View, Share } from 'react-native';
import Hyperlink from 'react-native-hyperlink'
import { Button, Card, Chip } from 'react-native-paper';
import API from './../API.js';
import UserName from './UserName.js';
import Media from './Media.js';
import Comment from "./Comment";
import NewComment from './NewComment.js';
import Moment from 'moment';
import { useSnapshot } from 'valtio';
import GlobalState from '../contexts/GlobalState.js';
import i18n from "../i18nMessages.js";
import ProfilePhotoCircle from './ProfilePhotoCircle.js';
import { posthog } from './../PostHog.js';
import { useNavigation } from '@react-navigation/native';


let Post = (props) => {
    const gState = useSnapshot(GlobalState);
    const viewer = gState.me;
    let [showCommentsB, changeshowCommentsB] = useState(props.showComments || false);
    let [post, changePost] = useState(props.post);
    let [likes, changeLikes] = useState(Object.keys(post.reactions).length);
    let [bookmarked, changeBookmarked] = useState(post.bookmarks && post.bookmarks.includes(viewer._id));
    let toProfileText = post.toProfile && post.toProfile !== post.profileid ?
        <ProfilePhotoCircle profileid={post.toProfile} small={true} /> : undefined;
    let cleanContent = post.content.replace(/@[A-z]+:.+\w/g, '').trim();
    const navigation = useNavigation();
    //cleanContent = convertLinks(cleanContent);
    const newComentAdded = (commentData) => {
        let newPostObj = { ...post };
        newPostObj.comments.push(commentData);
        changePost(newPostObj);
    };
    const newPostReaction = () => {
        let newPostObj = { ...post };
        if (!newPostObj.reactions[viewer._id]) {
            changeLikes(likes + 1);
            newPostObj.reactions[viewer._id] = { type: "like" };
            API.newPostReaction(post._id);
            posthog.capture(
                'post_clicked',
                {
                    post_id: post._id,
                }
            );
        } else {
            changeLikes(likes - 1);
            delete newPostObj.reactions[viewer._id];
            API.removePostReaction(viewer._id);
        }
        changePost(newPostObj);
    }
    const newPostBookmark = () => {
        if (!post.bookmarks || !post.bookmarks.includes(viewer._id)) {
            changeBookmarked(true);
            if (!post.bookmarks) post.bookmarks = [];
            post.bookmarks.push(viewer._id);
            API.newPostBookmark(post._id);
        } else {
            changeBookmarked(false);
            post.bookmarks = post.bookmarks.filter(id => id != viewer._id);
            API.removePostBookmark(post._id)
        }
    }
    const renderComment = ({ item }) => (
        <Comment comment={item} postid={post._id} />
    );
    return (
        <Card style={styles.card}>
            <Card.Content style={{
                padding: 0,
                margin: 0,
                marginBottom: 0
            }}>
                <Hyperlink linkDefault={true} linkStyle={{ color: '#2980b9' }}>
                    {!post.nonOrganicType ?
                        <View>
                            <ProfilePhotoCircle profileid={post.profileid} />
                            <View style={{ flexDirection: 'row', alignItems: 'center', margin: 0, marginLeft: 37, marginTop: -14, paddingBottom: 2 }}>
                                {toProfileText}

                            </View>
                            <Pressable onLongPress={() => {
                                if(cleanContent.length > 10){
                                    Share.share({
                                        message: cleanContent
                                    });
                                }
                            }}>
                                <Text style={{ fontSize: 16, padding: 3, paddingLeft: 40 }}>{
                                    cleanContent
                                }</Text>
                            </Pressable>
                            <Media content={post.content} postId={post._id} post={post} style={{ paddingTop: 2 }} />
                        </View> :
                        <View>
                            <Chip icon="new-releases" style={{ width: 100 }} >{i18n.t("message.news")}</Chip>
                            <Text style={{ fontSize: 18 }}>{cleanContent}</Text>
                            <Media content={post.content} />
                        </View>
                    }
                </Hyperlink>
            </Card.Content>
            <Card.Actions style={{ flexDirection: "row", flow: 4, fontSize: 16, marginLeft: 36, marginTop: -10 }}>
                <Button
                    icon={post.reactions[viewer._id] ? "favorite" : "favorite-border"}
                    labelStyle={{ fontSize: 17 }}
                    style={{ flow: 1 }}
                    onPress={newPostReaction}
                    color="#555"
                >
                    {likes}
                </Button>
                <Button icon="forum" labelStyle={{ fontSize: 17 }} style={{ flow: 1 }}
                    onPress={() => { 
                        // changeshowCommentsB(!showCommentsB) // Show comments
                        // Change view to single post
                        navigation.navigate("SinglePost", {
                            postid: post._id,
                        });
                    }}
                    color="#555"
                >
                    {post.comments.length}
                </Button>
                <Button icon="ios-share" style={{ flow: 1 }} labelStyle={{ fontSize: 17 }}
                    color="#555"
                    onPress={() => {
                        Share.share({
                            //message: "https://social.emmint.com/post/" + props.post._id,
                            url: "https://social.emmint.com/feed/post/" + props.post._id
                        });
                    }}></Button>
                <Button
                    icon={!bookmarked ? "bookmark-outline" : "bookmark"}
                    style={{ flow: 1 }}
                    labelStyle={{ fontSize: 17 }}
                    onPress={newPostBookmark}
                    color="#555"
                >
                </Button>
                <Text style={{ fontWeight: 'normal', fontSize: 12 }}>
                    {" " + Moment(post.createdAt).fromNow()}
                </Text>
            </Card.Actions>
            {showCommentsB && <NewComment postid={post._id} newComentAdded={newComentAdded} />}
            {
                showCommentsB &&
                    <FlatList
                        data={post.comments}
                        renderItem={renderComment}
                        keyExtractor={item => item.createdAt}
                    />
            }
        </Card>
    );
}

export default React.memo(Post);

const styles = StyleSheet.create({
    userName: {
        fontSize: 14,
        fontWeight: 'bold',
        marginBottom: 5,
        fontSize: 17,
    },
    card: {
        margin: 0,
        backgroundColor: "#FAFAFA",
        borderRadius: 0,
        marginBottom: 2,
        padding: 0
    },
    comment: {
        margin: 8,
        marginTop: 0,
        padding: 8
    }
});
