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

import { FlatList, Platform, Text, TouchableOpacity, View } from 'react-native';

import { RectButton } from 'react-native-gesture-handler';
import { MaterialIcons } from '@expo/vector-icons';
import { add, format, parseISO, sub } from 'date-fns';
import { styles } from './style';
import DateTimePicker from '@react-native-community/datetimepicker';
import Header from '../../components/Header';
import Load from '../../components/Load';
import Title from '../../components/Title';
import api from '../../services/api';
import fonts from '../../styles/fonts';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/core';
//import ArrowSvg from '../../assets/arrow.svg';


function Pagar() {
    const navigation: any = useNavigation();
    const [contas, setContas] = useState<any>([]);
    const [isLoading, setIsLoading] = 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);

    async function fetchData() {
        try {
            const date1 = format(date, 'yyyy-MM-dd');
            const dates2 = format(date2, 'yyyy-MM-dd')

            const response = await api.get(`pagar/listar.php?data=${date1}&data1=${dates2}`);

            if (response.data.resultado != "0") {
                setContas(response.data.resultado);
            } else {
                setContas([]);
            }

        } catch (error) {
            console.log(error);
        } finally {
            setIsLoading(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);
    };


    const Headers = ({ item }: any) => {
        return (
            <View style={{ marginBottom: 10, }}>
                <View style={styles.dates}>
                    <RectButton
                        style={styles.ButtonDates}
                        onPress={() => {
                            setDate(sub(new Date(), { years: 1 }));
                            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>
        );
    }


    const renderItem = ({ item }: any) => {
        const valor = String(item.valor).replace(".", ',');
        const data = parseISO(item.vencimento) || item.vencimento;
        const vencimento = format(data, 'dd/MM/yyyy');

        return (

            <View 
            style={
                (() => {
                    if (item.status == 'Pendente') {
                        return (
                            styles.CardContainer
                        )
                    } else {
                        return (
                            styles.CardContainerVerde
                        )
                    }
                })()
            }
            
           >

                <Text style={styles.Cliente}>{item.cliente}</Text>
                <Text style={styles.Valor}>R$ {valor}</Text>

                <View style={styles.Section}>
                    <MaterialIcons style={styles.Icon} name="attach-money" size={22} color="#c1c1c1" />
                    <Text style={styles.Entrada}>{item.saida}</Text>
                    <Text style={styles.Vencimento}>{vencimento}</Text>
                </View>

                <View style={styles.Footer}>
                    <Text style={styles.FooterText}>Frequência: <Text style={{ color: 'gray' }}>{item.frequencia}</Text></Text>
                </View>
            </View>
        )
    }
    
    const isEmpty = () => {
        return (
            <View style={{ justifyContent: 'center', alignItems: 'center', marginTop: 20, }}>
                <Text style={{ fontFamily: fonts.text, fontSize: 16 }}>Não tem nenhuma consulta para este dia.</Text>
            </View>
        )
    }

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

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

    return (
        <View style={{ flex: 1, backgroundColor: '#f2f2f2' }}>
            {show && (
                <DateTimePicker
                    testID="dateTimePicker"
                    value={date}
                    mode="date"
                    is24Hour={true}
                    display="calendar"
                    onChange={onChange}
                />
            )}

            {show2 && (
                <DateTimePicker
                    testID="dateTimePicker"
                    value={date2}
                    mode="date"
                    is24Hour={true}
                    display="calendar"
                    onChange={onChange2}
                />
            )}

            <Header />

            <Title title="Contas a Pagar" />

            {isLoading ?
                <Load />

                :

                <FlatList
                    data={contas}
                    renderItem={renderItem}
                    keyExtractor={(item) => (item.id)}
                    ListHeaderComponent={Headers}
                    initialNumToRender={5}
                    ListEmptyComponent={isEmpty}
                />

            }

                <View style={styles.containerFloat}>
                    <TouchableOpacity
                        style={styles.CartButton}
                        onPress={() => navigation.push("NovaContaPagar", { id_reg: '0' })}
                    >
                        <Ionicons name="add-outline" size={35} color="#fff" />
                    </TouchableOpacity>
                </View>

        </View>
    );
}

export default Pagar;