import React, { useState, useEffect } from 'react';
import {Image, AsyncStorage, ScrollView, Platform, Alert, Picker, Text, TextInput, View, TouchableOpacity, ActivityIndicator } from 'react-native';

import { RouteProp, useNavigation, useRoute } from '@react-navigation/core';
import { RectButton } from 'react-native-gesture-handler';
import { AntDesign, Ionicons } from '@expo/vector-icons';
import { styles } from './styles';
import { Success } from '../../lotties/Success';
import { TextInputMask } from 'react-native-masked-text';
import DateTimePicker from '@react-native-community/datetimepicker';
import { format } from 'date-fns';
import { showMessage, hideMessage } from "react-native-flash-message";
import * as ImagePicker from 'expo-image-picker';

import api from '../../services/api';
import url from '../../services/url';

type ParamList = {
    Detail: {
        id_reg: string;
        
    };
};


const NovoCliente: React.FC = () => {
    const navigation: any = useNavigation();

    const route = useRoute<RouteProp<ParamList, 'Detail'>>();
    const id_reg = route?.params?.id_reg;
       
    const [descricao, setDescricao] = useState("");
    const [valor, setValor] = useState("");
    const [fornecedor, setFornecedor] = useState("");
    const [frequencia, setFrequencia] = useState("");
    const [saida, setSaida] = useState("Caixa");
    
    const [lista_forn, setListaForn] = useState<any[]>([]);
    const [lista_freq, setListaFreq] = useState<any[]>([]);
    const [lista_saida, setListaSaida] = useState<any[]>([]);

    async function selectListaForn() {           
        try {
            const response = await api.get(`api/pagar/listar_forn.php`);
            setListaForn(response.data.resultado);
        } catch (error) {
            console.log(error);
        }
    }

    async function selectListaFreq() {           
        try {
            const response = await api.get(`api/pagar/listar_frequencia.php`);
            setListaFreq(response.data.resultado);
        } catch (error) {
            console.log(error);
        }
    }

    async function selectListaSaida() {           
        try {
            const response = await api.get(`api/pagar/listar_saidas.php`);
            setListaSaida(response.data.resultado);
        } catch (error) {
            console.log(error);
        }
    }
    

    const [dataVenc, setdataVenc] = useState(new Date());
    const [show, setShow] = useState(false);   
    

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

    
    const [image, setImage] = useState<any>();
    const [nomeImagem, setNomeImagem] = useState("");
    

    const pickImage = async () => {
        let result = await ImagePicker.launchCameraAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1,

        });

        if (result.cancelled) {
            return;
        }


        let localUri = result.uri;
        let filename: any = localUri.split('/').pop();
        setNomeImagem(filename);


        let match = /\.(\w+)$/.exec(filename);
        let type = match ? `image/${match[1]}` : `image`;


        let formData = new FormData();
        formData.append('photo', { uri: localUri, name: filename, type });
        setImage(result.uri);

        await api.post("api/pagar/upload-foto.php", formData);


    };


    const pickImageArquivos = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1,


        });

        if (result.cancelled) {
            return;
        }


        let localUri = result.uri;
        let filename: any = localUri.split('/').pop();
        setNomeImagem(filename);


        let match = /\.(\w+)$/.exec(filename);
        let type = match ? `image/${match[1]}` : `image`;

        let formData = new FormData();
        formData.append('photo', { uri: localUri, name: filename, type });
        setImage(result.uri);

        await api.post("api/pagar/upload-foto.php", formData);


    };
   
    const [sucess, setSucess] = useState(false);
    const [edit, setEdit] = useState(false);
    const [loading, setLoading] = useState(false);
   
    async function saveData() {  
        const user = await AsyncStorage.getItem('@user');     
        const dataVencF = format(dataVenc, 'yyyy-MM-dd');  
        
        if (valor == "") {
            showMessage({
                message: "Erro ao Salvar",
                description: 'Preencha os Campos Obrigatórios!',
                type: "warning",
            });
            return;
        }

        try {
            const obj = {
                id: id_reg,
                descricao: descricao,
                valor: valor,
                fornecedor: fornecedor,
                frequencia: frequencia,
                saida: saida,
                foto: nomeImagem,
                data_venc: dataVenc,                
                user: user,
                
            }

            const res = await api.post("api/pagar/salvar.php", obj);

            if (res.data.sucesso === false) {
                showMessage({
                    message: "Erro ao Salvar",
                    description: res.data.mensagem,
                    type: "warning",
                    duration: 3000,
                });

                return;
            }

            setSucess(true);
            showMessage({
                message: "Salvo com Sucesso",
                description: "Registro Salvo",
                type: "success",
                duration: 800,
            });
            navigation.push("Pagar")

        } catch (error) {
            Alert.alert("Ops", "Alguma coisa deu errado, tente novamente.");
            setSucess(false);
        }
    }

    

    async function loadData() {
        
        try {
            setLoading(true);
            if (id_reg != "0") {
                const res = await api.get(`api/pagar/listar_id.php?id=${id_reg}`);
                                 
               
                setValor(res.data.dados.valor);
                setDescricao(res.data.dados.descricao);
                setFornecedor(res.data.dados.fornecedor);
                setSaida(res.data.dados.saida);
                setFrequencia(res.data.dados.frequencia);               
                setdataVenc(new Date(res.data.dados.data_venc + 'T06:00'));                
                setImage(url + 'painel/images/contas/' + res.data.dados.foto);   
               
                setEdit(false);
                
            } else {
                setEdit(true);
            }
        } catch (error) {
            console.log('Error ao carregar os Dados');
        }
    }

     
        
    useEffect(() => {
        loadData().then(() => setLoading(false))
        .then(() => selectListaFreq())
        .then(() => selectListaForn())
        .then(() => selectListaSaida())
    }, [])

    if (loading === true) {
        return (
            <View style={{ flex: 1, backgroundColor: '#fff' }}>
                <ActivityIndicator style={{ marginTop: 100 }} color="#000" size="large" />
            </View>
        )
    }

    if (sucess) {
        return <Success />
    }
    

    return (
        <View style={{ flex: 1, marginTop: 20 }}>
            <View style={styles.Header}>
                <TouchableOpacity
                    style={styles.BackButton}
                    onPress={() => navigation.push("Pagar")}
                >
                    <Ionicons name="md-arrow-back-circle-outline" size={35} color="#484a4d" />

                </TouchableOpacity>
                {edit ?
                    <View style={styles.Title}>
                        <Text style={styles.TitleText}>Inserir Registro</Text>
                    </View>

                    :

                    <View style={styles.Title}>
                        <Text style={styles.TitleText}>Editar Registro</Text>
                    </View>
                }

            </View>

             <ScrollView>   
            <View>
                <Text style={styles.TitleInputs}>Descrição</Text>

                <TextInput
                    placeholder="Descrição da Conta"
                    onChangeText={(text) => setDescricao(text)}
                    value={descricao}
                    style={styles.TextInput}
                />
            </View> 


            <View>
                    <Text style={styles.TitleInputs}>Fornecedor</Text>
                    <View style={styles.Picker}>
                        <Picker
                            selectedValue={fornecedor}
                            onValueChange={(itemValue, itemIndex) => setFornecedor(itemValue)}
                            style={{ color: '#000' }}
                        >
                            {lista_forn.map((item: any) =>
                                <Picker.Item key={item.id} label={item.nome} value={item.id} />
                            )}  

                        </Picker>
                    </View>
                </View> 


               




               


            <View style={{ flexDirection: 'row', justifyContent: 'space-between', width: '95%', alignSelf: 'center' }}>
            
            <View style={{ width: '50%' }}>
                <View>
                <Text style={styles.TitleInputs}>Valor</Text>

                <TextInput
                    placeholder="Valor da Conta"
                    onChangeText={(text) => setValor(text)}
                    value={valor}
                    style={styles.TextInput}
                />
            </View> 

            
            </View>
            
            
            <View style={{ width: '50%' }}>
                        <Text style={styles.TitleInputsRow}>Vencimento</Text>

                        <TouchableOpacity
                            style={styles.pickDate}
                            onPress={() => setShow(true)}
                        >
                            <Text style={styles.date}>{format(dataVenc, 'dd/MM/yyyy')}</Text>
                            <AntDesign style={{ alignSelf: 'center', marginLeft: 25, }} name="caretdown" size={10} color="gray" />
                        </TouchableOpacity>
                    </View>

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

            </View>




            
            <View>
                    <Text style={styles.TitleInputs}>Frequência</Text>
                    <View style={styles.Picker}>
                        <Picker
                            selectedValue={frequencia}
                            onValueChange={(itemValue, itemIndex) => setFrequencia(itemValue)}
                            style={{ color: '#000' }}
                        >
                            {lista_freq.map((item: any) =>
                                <Picker.Item key={item.dias} label={item.nome} value={item.dias} />
                            )}  

                        </Picker>
                    </View>
                </View> 


                
            <View>
                    <Text style={styles.TitleInputs}>Saída</Text>
                    <View style={styles.Picker}>
                        <Picker
                            selectedValue={saida}
                            onValueChange={(itemValue, itemIndex) => setSaida(itemValue)}
                            style={{ color: '#000' }}
                            
                        >
                            <Picker.Item key="Caixa" label="Caixa" value="Caixa" />
                            <Picker.Item key="Cartão de Débito" label="Cartão de Débito" value="Cartão de Débito" />
                            <Picker.Item key="Cartão de Crédito" label="Cartão de Crédito" value="Cartão de Crédito" />
                            {lista_saida.map((item: any) =>
                                <Picker.Item key={item.nome} label={item.nome} value={item.nome} />
                            )}  

                        </Picker>
                    </View>
                </View> 






                <View style={{ flexDirection: 'row', justifyContent: 'space-between', width: '90%', alignSelf: "center", marginTop: 20 }}>
                    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>

                        <TouchableOpacity onPress={pickImage}>
                            <Ionicons name="camera" size={80} color="#706f6f" />
                        </TouchableOpacity>

                    </View>

                    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                        <TouchableOpacity onPress={pickImageArquivos}>
                            <Ionicons name="archive" size={80} color="#706f6f" />
                        </TouchableOpacity>

                    </View>
                </View>

                <View style={{alignItems: 'center', justifyContent: 'center', marginTop: 10 }}>
                    {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
                </View>               

           
                <RectButton
                    style={styles.Button}
                    onPress={() => {
                        setSucess(true);
                        saveData();
                        setSucess(false);
                    }}
                >
                    <Text style={styles.ButtonText}>Salvar Registro</Text>
                </RectButton>

                </ScrollView>

               
            {/* <NewPacientes /> */}

        </View>
    );
}

export default NovoCliente;