import React, { useEffect, useRef } from "react";
import { Searchbar, Title, IconButton } from 'react-native-paper';
import { StyleSheet, SafeAreaView, FlatList, View, ActivityIndicator } from 'react-native';
import API from "../API";
import GroupCard from "../components/GroupCard";
import AsyncStorage from '@react-native-async-storage/async-storage';
import i18n from "../i18nMessages.js";

const GROUPS_CACHE_KEY = 'groups_following';

const storeGroupsCache = async (value) => {
    try {
        const jsonValue = JSON.stringify(value || []);
        await AsyncStorage.setItem(GROUPS_CACHE_KEY, jsonValue);
    } catch (e) {
    }
};

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

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

    useEffect(() => {
        let subscribed = true;
        const getData = async () => {
            const cached = await getGroupsCache();
            if (subscribed) setGroups(Array.isArray(cached) ? cached : []);
            API.getFollowingGroups('').then((data) => {
                if (!subscribed) return;
                const liveGroups = Array.isArray(data?.groups) ? data.groups : [];
                setGroups(liveGroups);
                storeGroupsCache(liveGroups);
                setLoading(false);
            }).catch(() => {
                if (subscribed) setLoading(false);
            });
        };
        getData();
        return () => {
            subscribed = false;
            if (queryTimer.current) clearTimeout(queryTimer.current);
        }
    }, [])



    const onChangeSearch = query => {
        setSearchQuery(query);
        if (queryTimer.current) clearTimeout(queryTimer.current);
        setLoading(true);
        queryTimer.current = setTimeout(() => {
            if (!query) {
                return API.getFollowingGroups('').then((data) => {
                    const followingGroups = Array.isArray(data?.groups) ? data.groups : [];
                    setGroups(followingGroups);
                    storeGroupsCache(followingGroups);
                    setLoading(false);
                });
            }
            API.searchGroups(query).then((data) => {
                setGroups(Array.isArray(data?.groups) ? data.groups : []);
                setLoading(false);
            })

        }, 300);
    };
    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={i18n.t("message.searchGroups")}
                        onChangeText={onChangeSearch}
                        value={searchQuery}
                        clearButtonMode="while-editing"
                        blurOnSubmit={true}
                        onBlur={()=>{
                            setSearchVisible(false);
                        }}
                        forwardRef={searchTextBox}
                    />
                }
                </View>
                    <Title style={styles.title} >{searchQuery ? i18n.t("message.results") : i18n.t("message.yourGroups")}</Title>
                    </>
                }
                style={{backgroundColor: "#edf2f7",}}
            />
            {loading && !groups.length ? (
                <ActivityIndicator style={styles.loader} />
            ) : <></>}
        </SafeAreaView>
    )
}

export default Groups;

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