import React from 'react';
import { useEffect } from 'react';
import { useState } from 'react';
import fonts from "../../styles/fonts";
import {ScrollView, Text, Picker, AsyncStorage, Platform, 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/Pagar';
import Header from '../../components/Header';
import { format, add, sub } from 'date-fns';
import { RectButton } from 'react-native-gesture-handler';
import DateTimePicker from '@react-native-community/datetimepicker';

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

    

    const navigation: any = useNavigation();

    const [lista, setLista] = useState<any>([]);
    const [loading, setLoading] = useState(false); 
    const [nivelUsu, setNivelUsu] = useState("");

      
    const [onEndReachedCalledDuringMomentum, setMT] = useState(true);

    const [date, setDate] = useState<any>(new Date());
    const [show, setShow] = useState<any>(false);

    const [date2, setDate2] = useState<any>(new Date());
    const [show2, setShow2] = useState(false);

    const onChange = async (event: any, selectedDate: any) => {
        const currentDate = selectedDate || date;
        setShow(Platform.OS === 'ios');
        setDate(currentDate);
    };

    const onChange2 = async (event: any, selectedDate: any) => {
        const currentDate = selectedDate || date2;
        setShow2(Platform.OS === 'ios');
        setDate2(currentDate);
    };


    async function fetchData() {              
        
        try {
            
            const date1 = format(date, 'yyyy-MM-dd');
            const dates2 = format(date2, 'yyyy-MM-dd')
            
            const response = await api.get(`api/pagar/listar.php?data=${date1}&data1=${dates2}`);
            setLista(response.data.resultado);
            

        } catch (error) {
            console.log(error);
        }finally {
            setLoading(false);
        }
    }


    

    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>
        )
    }   

    useEffect(() => {
        fetchData();       
    }, []);

    useEffect(() => {
        Promise.all([date, date2]).then(() => {
            //setLoading(true);
            fetchData()
        })
    }, [date, date2]);

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

{show && (
                <DateTimePicker
                    testID="dateTimePicker"
                    value={date}
                    mode="date"
                    is24Hour={true}
                    display="default"
                    onChange={onChange}
                />
            )}

            {show2 && (
                <DateTimePicker
                    testID="dateTimePicker"
                    value={date2}
                    mode="date"
                    is24Hour={true}
                    display="default"
                    onChange={onChange2}
                />
            )}
            
            <Header title="Contas à Pagar"></Header>

            <View style={{ paddingHorizontal: 15, flex: 1, }}>
               
            <View style={{ marginBottom: 10, }}>
                <View style={styles.dates}>
                    <RectButton
                        style={styles.ButtonDates}
                        onPress={() => {
                            setDate(sub(new Date(), { years: 3 }));
                            setDate2(sub(new Date(), { days: 1 }));
                        }}
                    >
                        <Text style={styles.ButtonDatesText}>Vencidas</Text>
                    </RectButton>

                    <RectButton
                        style={styles.ButtonDates}
                        onPress={() => {
                            setDate(new Date());
                            setDate2(new Date());
                        }}
                    >
                        <Text style={styles.ButtonDatesText}>Hoje</Text>
                    </RectButton>

                    <RectButton
                        style={styles.ButtonDates}
                        onPress={() => {
                            setDate(add(new Date(), { days: 1 }));
                            setDate2(add(new Date(), { days: 1 }))
                        }}
                    >
                        <Text style={styles.ButtonDatesText}>Amanhã</Text>
                    </RectButton>
                </View>

                <View style={styles.Dates}>
                    <TouchableOpacity
                        style={styles.pickDate}
                        onPress={() => setShow(true)}
                    >
                        <Text style={{ fontFamily: fonts.text, fontSize: 16 }}>DE</Text>
                        <Text style={styles.date}>{format(date, 'dd/MM/yyyy')}</Text>
                    </TouchableOpacity>

                    <View style={{ alignSelf: 'center' }}>
                         <Ionicons name="md-arrow-forward-outline" size={30} color="#484a4d" />
                    </View>

                    <TouchableOpacity
                        style={styles.pickDate}
                        onPress={() => setShow2(true)}
                    >
                        <Text style={{ fontFamily: fonts.text, fontSize: 16 }}>ATÉ</Text>
                        <Text style={styles.date}>{format(date2, 'dd/MM/yyyy')}</Text>
                    </TouchableOpacity>
                </View>
            </View>
           

                <View style={{ flex: 1, height: Dimensions.get('window').height + 30, marginBottom:50}}>
                <ScrollView>
                    <FlatList
                        data={lista}
                        renderItem={renderItem}
                        keyExtractor={item => String(item.id)}
                        onEndReachedThreshold={0.1}
                        removeClippedSubviews
                        initialNumToRender={10}
                        onEndReached={(distanceFromEnd) => {
                          if (!onEndReachedCalledDuringMomentum) {
                            fetchData().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 style={styles.containerFloat}>
                    <TouchableOpacity
                        style={styles.CartButton}
                        onPress={() => navigation.push("NovaPagar", { id_reg: '0' })}
                    >
                        <Ionicons name="add-outline" size={35} color="#fff" />
                    </TouchableOpacity>
                </View>
            </View>
        </View>
    );
}

export default Clientes;