import { StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, SafeAreaView, FlatList } from 'react-native';
import API from './../API.js';
import Post from './../components/Post.js';

let Tags = ({ navigation, route }) => {
    let [Posts, setPosts] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        let subscribed = true;
        const getData = async () => {
            setPosts([]);
            console.log("Posts by tag", route.params.tag);
            API.getPostsByTag(route.params.tag).then((data) => {
                if(!subscribed) return 0;
                console.log("Posts by tag", data);
                setPosts(data);
                setLoading(false);
            });
        }
        getData();
        return ()=>{
            subscribed = false;
        }
    }, [route.params?.tag]);

    const renderPost = (({ item }) => {
        if (item.nonOrganicType)
            return (<></>);
        return (<Post post={item} />);
    });

    const header = (
        <View>
            <Text style={{ fontSize: 20, fontWeight: 'bold', padding: 10, alignContent: 'center', textAlign: 'center' }}>
                #{route.params.tag}
            </Text>
        </View>
    )

    return (
        <SafeAreaView style={styles.container}>
            <View>
                {!loading ?
                    <FlatList
                        data={Posts}
                        renderItem={renderPost}
                        keyExtractor={item => item.lastUpdated || item._id  || item.createdAt}
                        ListHeaderComponent={header}
                        refreshing={loading}
                        initialNumToRender={3}
                        maxToRenderPerBatch={3}
                        removeClippedSubviews={true}
                        onRefresh={() => {
                            API.getPostsByTag(route.params.tag).then(setPosts);
                        }}
                    /> :
                    <></> //TODO: Add empty profile card here
                }
            </View>
            <StatusBar style="auto" />
        </SafeAreaView>
    );
}

export default Tags;

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