import React, { useState, useEffect } from 'react';
import { StyleSheet, SafeAreaView, FlatList } from 'react-native';
import API from './../API.js';
import Post from './../components/Post.js';
import PostPopularUsers from '../components/PostPopularUsers.js';
import GlobalState from '../contexts/GlobalState.js';
import * as Linking from 'expo-linking';
import { posthog } from './../PostHog.js';
import * as Updates from 'expo-updates';

import AsyncStorage from '@react-native-async-storage/async-storage';

const storeFeed = async (value) => {
    try {
        const jsonValue = JSON.stringify(value)
        await AsyncStorage.setItem('feed', jsonValue)
    } catch (e) {
    }
}

const getFeed = async () => {
    try {
        const value = await AsyncStorage.getItem('feed')
        if (value !== null) {
            return JSON.parse(value);
        }
    } catch (e) {
        return []
    }
}

let prevLink = '';
const handleURL = (url, navigation) => {
    const { hostname, path, queryParams } = Linking.parse(url);
    if (!path) return;
    if (path.includes("feed/post/")) {
        const postid = path.substring(10);
        return navigation.navigate('SinglePost', { postid });
    }
    if (path.includes("feed/")) {
        const profileid = path.substring(5);
        return navigation.navigate('Profile', { profileid });
    }
    if (path === 'alert') {
        alert(queryParams.str);
    } else {
        //alert(path + " ::: " + queryParams);
    }
}

async function onFetchUpdateAsync() {
    try {
        const update = await Updates.checkForUpdateAsync();

        if (update.isAvailable) {
            await Updates.fetchUpdateAsync();
            await Updates.reloadAsync();
        }
    } catch (error) {
        // You can also add an alert() to see the error message in case of an error when fetching updates.
        console.log(`Error fetching latest Expo update: ${error}`);
    }
}

let Feed = ({ navigation, route }) => {
    let [Posts, setPosts] = useState([]);
    const flatListRef = React.useRef()
    console.log("Render Feed");
    const url = Linking.useURL();
    useEffect(() => {
        if (prevLink === url || !url) return;
        prevLink = url;
        handleURL(url, navigation);
    }, [url]);
    useEffect(() => {
        let subscribed = true;
        const getData = async () => {
            // TODO: Check for internet connection
            const internet = true;
            if (internet) {
                //byPass and load
                let loggedIn = await API.isLoggedIn();
                if (!loggedIn) return navigation.reset({
                    index: 0,
                    routes: [{ name: 'Login' }],
                });
                if (route.params && route.params.profileid) {
                    return navigation.navigate('Profile', { profileid: route.params.profileid });
                }
            }
            if (!route.params?.reRender) {
                API.getMe().then((me) => {
                    if (subscribed) {
                        GlobalState.me = me;
                        posthog.identify(me.userid,
                            {
                                name: me.profile.firstName,
                                profileid: me._id,
                                is_superuser: me.superuser,
                            }
                        );
                        posthog.capture('login');
                    }
                });
                console.log("Feed from cache")
                let cacheFeed = await getFeed() || [];
                if (cacheFeed.length && subscribed) setPosts(cacheFeed);
                console.log("Feed from server")
            }
            await onFetchUpdateAsync();
            flatListRef.current.scrollToOffset({ animated: true, offset: 0 })
            let posts = await API.getPosts();
            if (subscribed) {
                setPosts(posts);
                storeFeed(posts);
            }
            console.log("Feed, end useEffect")
        }
        getData()
        return () => {
            subscribed = false;
        }
    }, [route.params]);
    const renderPost = (({ item }) => {
        if (item.nonOrganicType === 'PopularUsers' || item.nonOrganicType === 'PopularGroups') {
            if (item.nonOrganicType === 'PopularUsers') {
                return (<PostPopularUsers post={item} />)
            }
            return (<></>);
        }
        return (<Post post={item} />);
    });


    return (
        <SafeAreaView>
            <FlatList
                data={Posts}
                renderItem={renderPost}
                keyExtractor={item => item.lastUpdated || item._id || item.ceatedAt} //This may refresh the component
                //ListHeaderComponent={<NewPost newPostCB={(newPost) => setPosts([newPost, ...Posts])} />}
                refreshing={Posts.length === 0}
                onRefresh={() => {
                    API.getPosts().then(setPosts);
                }}
                initialNumToRender={3}
                maxToRenderPerBatch={3}
                removeClippedSubviews={true}
                style={styles.container}
                ref={flatListRef}
            />
        </SafeAreaView>
    );
}

export default Feed;

const styles = StyleSheet.create({
    container: {
        backgroundColor: "#edf2f7",
    },
});
