import React from 'react';
import { useEffect } from 'react';
import { useState } from 'react';
import { RectButton } from 'react-native-gesture-handler';
import { Linking, Text, Modal, AsyncStorage, ActivityIndicator, FlatList, Image, TextInput, TouchableOpacity, View, Dimensions, Alert } from 'react-native';
import { styles } from './style';
import { MaterialIcons, EvilIcons, Ionicons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/core';

import api from '../../services/api';
import Card from '../../components/CardAniv';
import Header from '../../components/Header';

const Clientes: React.FC = () => {


    const navigation: any = useNavigation();

    const [clientes, setClientes] = useState<any>([]);
    const [loading, setLoading] = useState(false);
    const [page, setPage] = useState(1);
    const [totalItems, setTotalItems] = useState(0);
    const [busca, setBusca] = useState("Dia");
    const [titulo, setTitulo] = useState("Aniversáriantes do Dia");
    const [corDia, setCorDia] = useState("#a1a1a1");
    const [corMes, setCorMes] = useState("#c1c1c1");
    const [onEndReachedCalledDuringMomentum, setMT] = useState(true);
    const [id_ig, setIdIg] = useState("");
    const [fotoIgreja, setFotoIgreja] = useState("");


    async function loadData() {

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

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

        try {
            const response = await api.get(`apiIgreja/membros/listar-aniv.php?busca=${busca}&limite=10&igreja=${id_igreja.replace(/['"]+/g, '')}`);
            setClientes(response.data.resultado);
        } catch (error) {
            console.log(error)
        }
    }

    async function Buscar(busc:string, tit:string, cor1:string, cor2:string){
        setBusca(busc);
        setTitulo(tit);
        setCorMes(cor1);
        setCorDia(cor2);
        loadData()
    }


    const renderItem = function ({ item }: any) {
        return (
            <Card
                data={item}
            />
        )
    }

    function Footer(load: any) {
        if (!load) return null;

        return (
            <View style={styles.loading}>
                <ActivityIndicator size={25} color="#000" />
            </View>
        )
    }


    useEffect(() => {
        loadData();
    }, [page, totalItems, clientes]);

    return (
        <View style={styles.container}>

            <Header title={titulo} foto={fotoIgreja}></Header>

            <View style={{ paddingHorizontal: 15, flex: 1, }}>

                <View style={styles.dates}>
                    <RectButton
                        style={{
                            backgroundColor: corDia,
                            width: 100,
                            padding: 5,
                            height: 30,
                            borderRadius: 5,
                            justifyContent: "center",
                            alignItems: "center",
                            marginHorizontal: 5,
                        }}
                        onPress={() => {
                            Buscar("Dia", "Aniversáriantes do Dia", "#c1c1c1", "#a1a1a1")
                            
                        }}
                    >
                        <Text style={styles.ButtonDatesText}>Dia</Text>
                    </RectButton>

                    <RectButton
                        style={{
                            backgroundColor: corMes,
                            width: 100,
                            padding: 5,
                            height: 30,
                            borderRadius: 5,
                            justifyContent: "center",
                            alignItems: "center",
                            marginHorizontal: 5,
                        }}
                        onPress={() => {
                            Buscar("Mês", "Aniversáriantes do Mês", "#a1a1a1", "#c1c1c1");
                        }}
                    >
                        <Text style={styles.ButtonDatesText}>Mês</Text>
                    </RectButton>

                </View>

                <View style={{ flex: 1, height: Dimensions.get('window').height + 30, }}>
                    <FlatList
                        data={clientes}
                        renderItem={renderItem}
                        keyExtractor={item => String(item.id)}
                        onEndReachedThreshold={0.1}
                        removeClippedSubviews
                        initialNumToRender={10}
                        onEndReached={(distanceFromEnd) => {
                            if (!onEndReachedCalledDuringMomentum) {
                                loadData().then(() => setLoading(false));
                                setMT(true);
                            }
                        }}
                        ListFooterComponent={(distanceFromEnd) => {
                            if (!onEndReachedCalledDuringMomentum) {
                                return <Footer load={loading} />
                            } else {
                                return <View></View>
                            }
                        }}
                        onMomentumScrollBegin={() => setMT(false)}
                        windowSize={10}
                        getItemLayout={(data, index) => (
                            { length: 50, offset: 50 * index, index }
                        )}
                    />
                </View>


            </View>


        </View>


    );
}



export default Clientes;