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

import {AsyncStorage, ScrollView, ActivityIndicator, FlatList, Image, TextInput, TouchableOpacity, View, Dimensions, Alert } from 'react-native';
import { styles } from './style';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/core';

import api from '../../services/api';
import Grid from '../../components/Grids/Usuarios';
import Header from '../../components/Header';

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

    

    const navigation: any = useNavigation();

    const [lista, setLista] = useState<any>([]);
    const [loading, setLoading] = useState(false);
    const [page, setPage] = useState(1);
    const [totalItems, setTotalItems] = useState(0);
    const [busca, setBusca] = useState("");
    const [onEndReachedCalledDuringMomentum, setMT] = useState(true);

    async function loadData() {
        const nivel:any = await AsyncStorage.getItem('@nivel'); 
               
        try {
            const response = await api.get(`api/usuarios/listar.php?pagina=${page}&limite=10&nivel=${nivel.replace(/['"]+/g, '')}`);

            if(lista.length >= response.data.totalItems) return;

            if (loading === true) return;
      
            setLoading(true);
      
            setLista([...lista, ...response.data.resultado]);
            setPage(page + 1);
          } catch (error) {
            console.log(error)
          }
    }
    

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

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

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

    async function Search() {
        const nivel:any = await AsyncStorage.getItem('@nivel'); 
       const response = await api.get(`api/usuarios/buscar.php?buscar=${busca}&nivel=${nivel.replace(/['"]+/g, '')}`);
       
       setLista(response.data.resultado);
    }

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

    return (
        <View style={styles.container}>
            
            <Header title="Lista de Usuários"></Header>

            <View style={{ paddingHorizontal: 15, flex: 1, }}>
                <View style={styles.containerSearch}>
                    <TextInput
                        style={styles.search}
                        placeholder="Buscar Por Email ou Nome"
                        placeholderTextColor="gray"
                        keyboardType="default"
                        onChangeText={(busca) => setBusca(busca)}
                        returnKeyType="search"
                        onTextInput= {() => Search()}
                    />

                    <TouchableOpacity
                        style={styles.iconSearch}
                        onPress={() => Search()}
                    >
                        <Ionicons name="search-outline" size={28} color="gray" />
                    </TouchableOpacity>
                </View>

                <View style={{ flex: 1, height: Dimensions.get('window').height + 30, }}>
                <ScrollView>
                    <FlatList
                        data={lista}
                        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 }
                        )}
                    />
                    </ScrollView>
                </View>

                
            </View>
        </View>
    );
}

export default Clientes;