import React, { useEffect } from "react";
import { Searchbar } from 'react-native-paper';
import { StyleSheet, SafeAreaView, FlatList, Text } from 'react-native';
import API from "../API";
import ProfileCardHorizontal from "../components/ProfileCardHorizontal";
import { useSnapshot } from 'valtio';
import GlobalState from '../contexts/GlobalState.js';
import ProfileHeader from "../components/ProfileHeader";

const Search = () => {
    const viewer = useSnapshot(GlobalState).me;
    const [searchQuery, setSearchQuery] = React.useState('');
    const [profiles, setProfiles] = React.useState([]);
    const [queryTimer, setQueryTimer] = React.useState(0);

    useEffect(() => {
        let subscribed = true;
        // Igonred as we are using following
        //API.searchProfiles('').then((data) => {
        //    if (subscribed && data.profiles){
        //        setProfiles(filteredProfiles);
        //    }
        //});
        return () => {
            subscribed = false;
        }
    }, [])

    const onChangeSearch = query => {
        setSearchQuery(query);
        if (queryTimer) clearTimeout(queryTimer);
        let timerId = setTimeout(() => {
            API.searchProfiles(query).then((data) => {
                console.log("DataChange Search view")
                setProfiles(data.profiles || []);
            });
        }, 300);
        setQueryTimer(timerId);
    };
    const renderProfile = (({ item }) => {
        return (<ProfileCardHorizontal profileObj={item} />);
    });
    const renderFollowing = (({ item }) => {
        return (<ProfileCardHorizontal profileid={item} />);
    });
    const followers = viewer.following.slice().reverse().slice(0, 10);
    return (
        <SafeAreaView style={{ flex: 1, backgroundColor: "#edf2f7", }}>
            <Searchbar
                placeholder="Search Users"
                onChangeText={onChangeSearch}
                value={searchQuery}
            />
            {
            searchQuery.length ? 
            <FlatList
                contentContainerStyle={styles.container}
                numColumns={1}
                data={profiles}
                renderItem={renderProfile}
                keyExtractor={item => item._id}
            /> :
            <FlatList
                contentContainerStyle={styles.container}
                numColumns={1}
                data={followers}
                renderItem={renderFollowing}
                keyExtractor={item => item}
                ListHeaderComponent={<Text style={{fontSize:20, padding:10, alignSelf: "center"}}>Recently Following</Text>}
            />
        }
        </SafeAreaView>
    )
}

export default Search;

const styles = StyleSheet.create({
    container: {
        padding: 5,
    },
});
