import React, { useEffect, useRef } from "react";
import { Searchbar, Title, IconButton } from 'react-native-paper';
import { StyleSheet, SafeAreaView, FlatList, View } from 'react-native';
import API from "../API";
import GroupCard from "../components/GroupCard";

const Groups = ({navigation}) => {
    const [searchQuery, setSearchQuery] = React.useState('');
    const [searchVisible, setSearchVisible] = React.useState(false);
    const [groups, setGroups] = React.useState([]);
    const [queryTimer, setQueryTimer] = React.useState(0);
    const searchTextBox = useRef(null);

    useEffect(() => {
        let subscribed = true;
        API.getFollowingGroups('').then((data) => {
            if (subscribed)
                setGroups(data?.groups || []);
        });
        return () => {
            subscribed = false;
        }
    }, [])



    const onChangeSearch = query => {
        setSearchQuery(query);
        if (queryTimer) clearTimeout(queryTimer);
        let timerId = setTimeout(() => {
            if (!query) {
                return API.getFollowingGroups('').then((data) => {
                    setGroups(data.groups || []);
                });
            }
            API.searchGroups(query).then((data) => {
                setGroups(data.groups || []);
            })

        }, 300);
        setQueryTimer(timerId);
    };
    const renderProfile = (({ item }) => {
        return (<GroupCard profileObj={item} />);
    });
    return (
        <SafeAreaView style={{ flex: 1 }}>
            <FlatList
                contentContainerStyle={styles.container}
                numColumns={1}
                data={groups}
                renderItem={renderProfile}
                keyExtractor={item => item._id}
                ListHeaderComponent={
                    <>
                    <View style={{
                position: "absolute",
                top: 0,
                left: 0,
                width: "100%",
                zIndex: 100
            }}>
                {!searchVisible ? 
                    <View style={{
                        alignSelf:"flex-end",
                        flex:1,
                        flexDirection: "row"
                    }}>
                        <IconButton icon={'add'} size={35} onPress={()=>{
                            navigation.navigate('NewGroup');
                        }} />
                        <IconButton icon={'search'} size={35} onPress={()=>{
                            setSearchVisible(true);
                            console.log(searchTextBox)
                            //searchTextBox.current.focus();
                        }} />
                    </View> :
                    <Searchbar
                        placeholder="Search Groups"
                        onChangeText={onChangeSearch}
                        value={searchQuery}
                        clearButtonMode="while-editing"
                        blurOnSubmit={true}
                        onBlur={()=>{
                            setSearchVisible(false);
                        }}
                        forwardRef={searchTextBox}
                    />
                }
                </View>
                    <Title style={styles.title} >{searchQuery ? "Results:" : "Your Groups:"}</Title>
                    </>
                }
                style={{backgroundColor: "#edf2f7",}}
            />
        </SafeAreaView>
    )
}

export default Groups;

const styles = StyleSheet.create({
    container: {
        padding: 0,
    },
    title: {
        padding: 10,
        paddingTop:5,
        fontSize: 30,
        marginTop: 15,
        fontWeight: "bold",
        color: "#777"
    }
});
