import React, { useState, useEffect } from 'react';
import { AsyncStorage, Image, Platform, ScrollView, Alert, Picker, Text, TextInput, View, TouchableOpacity, ActivityIndicator } from 'react-native';
import { format } from 'date-fns';
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 { showMessage, hideMessage } from "react-native-flash-message";
import url from '../../services/url';
import api from '../../services/api';
import * as ImagePicker from 'expo-image-picker';

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 [nome, setNome] = useState("");
    const [celular, setCelular] = useState("");
    const [cpf, setCPF] = useState("");
    const [endereco, setEndereco] = useState("");
    const [email, setEmail] = useState("");
    const [ativo, setAtivo] = useState("Sim");
    const [estado, setEstado] = useState("Solteiro");

    const [lista_cargo, setListaCargo] = useState<any[]>([]);
    const [cargo, setCargo] = useState("");

    const [dataNasc, setdataNasc] = useState(new Date());
    const [show, setShow] = useState(false);

    const [dataBat, setdataBat] = useState(new Date());
    const [show2, setShow2] = useState(false);

    const [batizado, setBatizado] = useState("Não");

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

    const onChange2 = async (event: any, selectedDate: any) => {
        const currentDate = selectedDate || dataBat;
        setShow2(Platform.OS === 'ios');
        setdataBat(currentDate);
        setBatizado("");
    };

    const [sucess, setSucess] = useState(false);
    const [edit, setEdit] = useState(false);
    const [loading, setLoading] = useState(false);

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


    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("apiIgreja/membros/upload.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("apiIgreja/membros/upload.php", formData);


    };


    async function selectListaCargos() {
        try {
            const response = await api.get('apiIgreja/membros/listar_cargos.php');

            setListaCargo(response.data.resultado);
        } catch (error) {
            console.log(error);
        }
    }

    async function saveData() {
        

        const id_igreja: any = await AsyncStorage.getItem('@id_igreja');

        const dataNascF = format(dataNasc, 'yyyy-MM-dd');
        const dataBatF = format(dataBat, 'yyyy-MM-dd');

        if (nome == "" || cpf == "") {
            showMessage({
                message: "Erro ao Salvar",
                description: 'Preencha os Campos Obrigatórios!',
                type: "warning",
            });
            return;
        }



        try {
            const obj = {
                id: id_reg,
                nome: nome,
                celular: celular,
                endereco: endereco,
                email: email,
                ativo: ativo,
                estado: estado,
                cpf: cpf,
                dataNasc: dataNascF,
                dataBat: dataBatF,
                cargo: cargo,
                foto: nomeImagem,
                igreja: id_igreja.replace(/['"]+/g, ''),
                batizado:batizado
            }

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

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

                return;
            }

            setSucess(true);

            showMessage({
                message: "Salvo",
                description: 'Registro Salvo com Sucesso!!',
                type: "success",
            });

            navigation.push("Pessoas")

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



    async function loadData() {

        selectListaCargos()

        try {
            setLoading(true);

            if (id_reg != "0") {
                const res = await api.get(`apiIgreja/membros/listar_id.php?id=${id_reg}`);

                if (res.data.dados.dataBat == '0000-00-00') {
                    const dataBat2 = new Date();
                    setdataBat(dataBat2);
                    setBatizado("Não");
                } else {
                    setdataBat(new Date(res.data.dados.dataBat + 'T06:00'));
                    setBatizado("Sim");
                }

                setNome(res.data.dados.nome);
                setCelular(res.data.dados.telefone);
                setEndereco(res.data.dados.endereco);
                setEmail(res.data.dados.email);
                setAtivo(res.data.dados.ativo);
                setCPF(res.data.dados.cpf);
                setCargo(res.data.dados.cargo);
                setEstado(res.data.dados.estado);
                setdataNasc(new Date(res.data.dados.dataNasc + 'T06:00'));

                setImage(url + 'sistema/img/membros/' + res.data.dados.tumb);
                
                setEdit(false);

            } else {
                setEdit(true);
            }
        } catch (error) {
            console.log('Error ao carregar os Dados');
        }
    }



    useEffect(() => {
        loadData()
            .then(() => setLoading(false))
            .then(() => selectListaCargos())
    }, [])

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

    if (sucess) {

    }


    return (
        <View style={{ flex: 1, marginTop: 20 }}>
            <View style={styles.Header}>
                <TouchableOpacity
                    style={styles.BackButton}
                    onPress={() => navigation.goBack()}
                >
                    <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}>Nome completo</Text>

                    <TextInput
                        placeholder="Nome completo"
                        onChangeText={(text) => setNome(text)}
                        value={nome}
                        style={styles.TextInput}
                    />
                </View>

                <View style={{ flexDirection: 'row', justifyContent: 'space-between', width: '95%', alignSelf: 'center' }}>

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

                        <TextInputMask
                            style={styles.TextInput}
                            type={'cel-phone'}
                            options={{
                                maskType: 'BRL',
                                withDDD: true,
                                dddMask: '(31) '
                            }}
                            value={celular}
                            onChangeText={text => setCelular(text)}
                            placeholder="Telefone Celular"
                        />
                    </View>


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

                        <TextInputMask
                            style={styles.TextInput}
                            type={'cpf'}
                            value={cpf}
                            onChangeText={text => setCPF(text)}
                            placeholder="CPF"
                        />
                    </View>

                </View>

                <View>
                    <Text style={styles.TitleInputs}>Endereço</Text>

                    <TextInput
                        placeholder="Rua A Nº 50 Bairro Teste"
                        onChangeText={(text) => setEndereco(text)}
                        value={endereco}
                        style={styles.TextInput}

                    />
                </View>

                <View>
                    <Text style={styles.TitleInputs}>Email</Text>

                    <TextInput
                        placeholder="Email"
                        onChangeText={(text) => setEmail(text)}
                        value={email}
                        style={styles.TextInput}

                    />
                </View>


                <View>
                    <Text style={styles.TitleInputs}>Selecionar Cargo</Text>
                    <View style={styles.TextInput}>
                        <Picker
                            selectedValue={cargo}
                            onValueChange={(itemValue, itemIndex) => setCargo(itemValue)}
                        >

                            {lista_cargo.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%' }}>
                        <Text style={styles.TitleInputsRow}>Estado Civil</Text>
                        <View style={styles.TextInput}>
                            <Picker
                                selectedValue={estado}
                                onValueChange={(itemValue, itemIndex) => setEstado(itemValue)}
                                style={{ color: '#000' }}
                            >
                                <Picker.Item label="Solteiro" value="Solteiro" />
                                <Picker.Item label="Casado" value="Casado" />

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

                    <View style={{ width: '50%' }}>
                        <Text style={styles.TitleInputsRow}>Ativo</Text>
                        <View style={styles.TextInput}>
                            <Picker
                                selectedValue={ativo}
                                onValueChange={(itemValue, itemIndex) => setAtivo(itemValue)}
                                style={{ color: '#000' }}
                            >
                                <Picker.Item label="Sim" value="Sim" />
                                <Picker.Item label="Não" value="Não" />

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

                </View>



                <View style={{ flexDirection: 'row', justifyContent: 'space-between', width: '95%', alignSelf: 'center' }}>


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

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

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


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

                        <TouchableOpacity
                            style={styles.pickDate}
                            onPress={() => setShow2(true)}
                        >
                            {(() => {
                                if (batizado == 'Não') {
                                    return(
                                        <Text style={styles.date}>Não Batizado</Text>
                                    )
                                    
                                }else{
                                    return(
                                        <Text style={styles.date}>{format(dataBat, 'dd/MM/yyyy')}</Text>
                                    )                                   
                                }
                            })()}

                            
                            <AntDesign style={{ alignSelf: 'center', marginLeft: 25, }} name="caretdown" size={10} color="gray" />
                        </TouchableOpacity>
                    </View>

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


                </View>


                <View style={{ flex: 1, 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={{ flex: 1, alignItems: 'center', justifyContent: 'center', marginTop: 10 }}>
                    {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
                </View>


            </ScrollView>


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


            {/* <NewPacientes /> */}

        </View>
    );
}

export default NovoCliente;