import React, { useEffect, useState } from 'react';

import {
    SafeAreaView,
    Text,
    View,
    ScrollView,
    TouchableOpacity,
    Image,
    ActivityIndicator,
    RefreshControl,
    StatusBar,
    AsyncStorage,
    Alert,

} from 'react-native';

import { MaterialIcons } from '@expo/vector-icons';
import { styles } from './style';
import { DrawerActions, useNavigation, useRoute, RouteProp } from '@react-navigation/core';
import { AnimatedCircularProgress } from 'react-native-circular-progress';

import api from '../../services/api';
import url from '../../services/url';
import Load from '../../components/Load';
import { useIsFocused } from '@react-navigation/native';


export default function Home() {

    const navigation: any = useNavigation();
    const isFocused = useIsFocused();


    const [dados, setDados] = useState<any>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [refreshing, setRefreshing] = React.useState(false);
    const [usu, setUsu] = React.useState('');
    const [nivel, setNivel] = useState('');


    async function recuperarIdIgreja() {
        const id_igreja: any = await AsyncStorage.getItem('@id_igreja');
        listarDados(id_igreja.replace(/['"]+/g, ''))      
        
    }

    async function listarDados(id: string) {

        const nivel_usu: any = await AsyncStorage.getItem('@nivel');
        setNivel(nivel_usu.replace(/['"]+/g, ''))

        if (id != undefined && id != "") {

        } else {
            return;
        }

        try {
            const response = await api.get(`apiIgreja/dashboard/ListAllCards.php?id=${id}`);
            setDados(response.data);            
                       

        } catch (error) {
            console.log("Error");
        } finally {
            setIsLoading(false);
            setRefreshing(false);
            
            
        }
    }

    useEffect(() => {
        listarDados("").then(() =>
            recuperarIdIgreja().then(() => listarDados("")))
    }, [])

    useEffect(() => {
        listarDados("");
    }, [isFocused]);

    const onRefresh = () => {
        setRefreshing(true);
        recuperarIdIgreja();

    };


    const porcent = (dados.tarefasConcluidas / dados.totalTarefas) * 100;


    return (
        <View style={{ flex: 1 }}>
            <StatusBar barStyle="light-content" />
            <View style={{ flex: 1 }}>
                <View style={styles.header}>
                    <View style={styles.containerHeader}>

                        <TouchableOpacity
                            style={styles.menu}
                            onPress={() => navigation.dispatch(DrawerActions.openDrawer())}
                        >
                            <MaterialIcons name="menu" size={35} color="white" />
                        </TouchableOpacity>

                        <Image style={styles.logo} source={{ uri: (url + 'sistema/img/igrejas/' + dados.foto_igreja) }} />
                        <Text style={styles.tituloHeader}>{dados.nome_igreja}</Text>

                        {(() => {
                            if (nivel == 'bispo') {
                                return(
                                    <TouchableOpacity
                                    style={styles.logoutHome}
                                    onPress={() => navigation.navigate("HomeInicio")}
                                >
                                    <MaterialIcons name="logout" size={20} color="white" />
                                </TouchableOpacity>
                                )
                               
                            }
                         })()}
                    </View>
                </View>

                {isLoading ?
                    <Load /> :

                    <ScrollView
                        style={{ flex: 1 }}
                        showsVerticalScrollIndicator={false}
                        nestedScrollEnabled={true}
                        refreshControl={
                            <RefreshControl
                                refreshing={refreshing}
                                onRefresh={onRefresh}
                            />
                        }
                    >

                        <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', width: '100%', alignSelf: "center", padding: 10, backgroundColor: '#FFF' }}>
                            <View style={{ width: '40%', flex: 1, flexDirection: 'row', justifyContent: 'center' }}>
                            <TouchableOpacity                                    
                                    onPress={() => navigation.push("Aniv")}
                                >
                                <Image style={styles.imganiv} source={require('../../assets/aniversario.png')} />
                                </TouchableOpacity>
                                <TouchableOpacity                                    
                                    onPress={() => navigation.push("Aniv")}
                                >
                                <Text style={styles.textProgressTitulo}>Hoje ({dados.totalAniversariantes})</Text>
                            </TouchableOpacity>
                            </View>
                            <View style={{ width: '60%', justifyContent: 'center' }}>
                                <Text style={styles.textProgressTitulo}>Saldo Mês <Text style={{ color: dados.classeSaldo }}>R$ {dados.saldoMes}</Text></Text>
                            </View>
                        </View>

                        <View style={styles.circleProgressView}>
                            <View style={styles.textProgressContainer}>
                                <Text style={styles.textProgressTitle}>Tarefas</Text>
                                <Text style={styles.textProgress}>{dados.tarefasConcluidas} de {dados.totalTarefas} finalizadas</Text>

                            </View>

                            <AnimatedCircularProgress
                                size={70}
                                width={7}
                                fill={porcent}
                                tintColor="#00e0ff"
                                backgroundColor="#e0e0e0"
                                lineCap={"round"}
                            >
                                {
                                    (fill) => (
                                        <Text style={styles.numberInside}>{dados.tarefasConcluidas}</Text>
                                    )
                                }
                            </AnimatedCircularProgress>
                        </View>


                        <View style={styles.containerBox}>

                            <TouchableOpacity onPress={() => navigation.push("Pessoas")}>
                                <View>
                                    <View style={styles.box}>
                                        <MaterialIcons style={styles.iconRegistered} name="people-alt" size={70} color="#17a2b8" />
                                        <View style={styles.textos}>
                                            <Text style={styles.rText}>Membros</Text>
                                            <Text style={styles.lenghtText}>{dados.quantidade_clientes}</Text>
                                        </View>
                                    </View>
                                    <Text style={styles.textFooter}>Membros Cadastrados</Text>
                                </View>
                            </TouchableOpacity>

                        </View>



                        <View style={styles.containerBox}>

                            <TouchableOpacity onPress={() => navigation.push("Pessoas")}>
                                <View>
                                    <View style={styles.box}>
                                        <MaterialIcons style={styles.iconRegistered} name="monetization-on" size={70} color="#077840" />
                                        <View style={styles.textos}>
                                            <Text style={styles.rText}>Dízimos</Text>
                                            <Text style={styles.lenghtText}>R$ {dados.totalDizimos}</Text>
                                        </View>
                                    </View>
                                    <Text style={styles.textFooter}>Total de Dízimos do Mês</Text>
                                </View>
                            </TouchableOpacity>

                        </View>



                        <View style={styles.containerBox}>

                            <TouchableOpacity onPress={() => navigation.push("Pessoas")}>
                                <View>
                                    <View style={styles.box}>
                                        <MaterialIcons style={styles.iconRegistered} name="money-off" size={70} color="#d12a08" />
                                        <View style={styles.textos}>
                                            <Text style={styles.rText}>Gastos</Text>
                                            <Text style={styles.lenghtTextRed}>R$ {dados.totalGastos}</Text>
                                        </View>
                                    </View>
                                    <Text style={styles.textFooter}>Total de Gastos do Mês</Text>
                                </View>
                            </TouchableOpacity>

                        </View>




                        <View style={styles.containerBox}>

                            <TouchableOpacity onPress={() => navigation.push("Pessoas")}>
                                <View>
                                    <View style={styles.box}>
                                        <MaterialIcons style={styles.iconRegistered} name="monetization-on" size={70} color="#03739c" />
                                        <View style={styles.textos}>
                                            <Text style={styles.rText}>Ofertas</Text>
                                            <Text style={styles.lenghtText}>R$ {dados.totalOfertas}</Text>
                                        </View>
                                    </View>
                                    <Text style={styles.textFooter}>Total de Ofertas do Mês</Text>
                                </View>
                            </TouchableOpacity>

                        </View>




                        <View style={styles.containerBox}>

                            <TouchableOpacity onPress={() => navigation.push("Pessoas")}>
                                <View>
                                    <View style={styles.box}>
                                        <MaterialIcons style={styles.iconRegistered} name="credit-card" size={70} color="#077840" />
                                        <View style={styles.textos}>
                                            <Text style={styles.rText}>Vendas</Text>
                                            <Text style={styles.lenghtText}>R$ {dados.totalVendas}</Text>
                                        </View>
                                    </View>
                                    <Text style={styles.textFooter}>Total de Vendas do Mês</Text>
                                </View>
                            </TouchableOpacity>

                        </View>



                        <View style={styles.containerBox}>

                            <TouchableOpacity onPress={() => navigation.push("Pessoas")}>
                                <View>
                                    <View style={styles.box}>
                                        <MaterialIcons style={styles.iconRegistered} name="monetization-on" size={70} color="#03739c" />
                                        <View style={styles.textos}>
                                            <Text style={styles.rText}>Doações</Text>
                                            <Text style={styles.lenghtText}>R$ {dados.totalDoacoes}</Text>
                                        </View>
                                    </View>
                                    <Text style={styles.textFooter}>Total de Doações do Mês</Text>
                                </View>
                            </TouchableOpacity>

                        </View>



                        <View style={styles.containerBox}>

                            <TouchableOpacity onPress={() => navigation.push("Pessoas")}>
                                <View>
                                    <View style={styles.box}>
                                        <MaterialIcons style={styles.iconRegistered} name="person-pin" size={70} color="#17a2b8" />
                                        <View style={styles.textos}>
                                            <Text style={styles.rText}>Grupos</Text>
                                            <Text style={styles.lenghtText}>{dados.gruposCadastrados}</Text>
                                        </View>
                                    </View>
                                    <Text style={styles.textFooter}>Total de Grupos Cadastrados</Text>
                                </View>
                            </TouchableOpacity>

                        </View>



                        <View style={styles.containerBox}>

                            <TouchableOpacity onPress={() => navigation.push("Pessoas")}>
                                <View>
                                    <View style={styles.box}>
                                        <MaterialIcons style={styles.iconRegistered} name="people-outline" size={70} color="#17a2b8" />
                                        <View style={styles.textos}>
                                            <Text style={styles.rText}>Células</Text>
                                            <Text style={styles.lenghtText}>{dados.celulasCadastradas}</Text>
                                        </View>
                                    </View>
                                    <Text style={styles.textFooter}>Total de Células Cadastrados</Text>
                                </View>
                            </TouchableOpacity>

                        </View>



                        <View style={styles.containerBox}>

                            <TouchableOpacity onPress={() => navigation.push("Patrimonios")}>
                                <View>
                                    <View style={styles.box}>
                                        <MaterialIcons style={styles.iconRegistered} name="pie-chart" size={70} color="#17a2b8" />
                                        <View style={styles.textos}>
                                            <Text style={styles.rText}>Patrimônio / Itens</Text>
                                            <Text style={styles.lenghtText}>{dados.patCadastrados}</Text>
                                        </View>
                                    </View>
                                    <Text style={styles.textFooter}>Patrimônios Cadastrados</Text>
                                </View>
                            </TouchableOpacity>

                        </View>



                        <View style={styles.containerBox}>

                            <TouchableOpacity onPress={() => navigation.push("Pessoas")}>
                                <View>
                                    <View style={styles.box}>
                                        <MaterialIcons style={styles.iconRegistered} name="money-off" size={70} color="#d12a08" />
                                        <View style={styles.textos}>
                                            <Text style={styles.rText}>Pagar Hoje</Text>
                                            <Text style={styles.lenghtTextRed}>  {dados.pagarHoje}</Text>
                                        </View>
                                    </View>
                                    <Text style={styles.textFooter}>Contas à Pagar Hoje</Text>
                                </View>
                            </TouchableOpacity>

                        </View>



                        <View style={styles.containerBox}>

                            <TouchableOpacity onPress={() => navigation.push("Pessoas")}>
                                <View>
                                    <View style={styles.box}>
                                        <MaterialIcons style={styles.iconRegistered} name="money-off" size={70} color="#038026" />
                                        <View style={styles.textos}>
                                            <Text style={styles.rText}>Receber Hoje</Text>
                                            <Text style={styles.lenghtText}> {dados.receberHoje}</Text>
                                        </View>
                                    </View>
                                    <Text style={styles.textFooter}>Contas à Receber Hoje</Text>
                                </View>
                            </TouchableOpacity>

                        </View>



                        <View style={styles.containerBox}>

<TouchableOpacity onPress={() => navigation.push("Pessoas")}>
    <View>
        <View style={styles.box}>
            <MaterialIcons style={styles.iconRegistered} name="monetization-on" size={70} color="#d12a08" />
            <View style={styles.textos}>
                <Text style={styles.rText}>Pagar Vencidas</Text>
                <Text style={styles.lenghtTextRed}>  {dados.pagarVencidas}</Text>
            </View>
        </View>
        <Text style={styles.textFooter}>Contas à Pagar Vencidas</Text>
    </View>
</TouchableOpacity>

</View>


                    </ScrollView>
                }
            </View>
        </View>


    )
}