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 NovoRegistro: React.FC = () => {
    const navigation: any = useNavigation();

    const route = useRoute<RouteProp<ParamList, 'Detail'>>();
    const id_reg = route?.params?.id_reg;

    const [nome, setNome] = useState("");
    const [codigo, setCodigo] = useState("");
    const [descricao, setDescricao] = useState("");
    const [entrada, setEntrada] = useState("Compra");
    const [valor, setValor] = useState("");
    const [ativo, setAtivo] = useState("Sim");
    const [doador, setDoador] = useState("");
    const [obs, setObs] = useState("");

    const [dataCad, setDataCad] = useState(new Date());
    const [show, setShow] = useState(false);


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



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


    };



    async function saveData() {

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

        const dataCadF = format(dataCad, 'yyyy-MM-dd');


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



        try {
            const obj = {
                id: id_reg,
                nome: nome,
                codigo: codigo,
                descricao: descricao,
                valor: valor,
                entrada: entrada,
                doador: doador,
                dataCad: dataCadF,
                obs: obs,
                ativo: ativo,
                foto: nomeImagem,
                igreja: id_igreja.replace(/['"]+/g, ''),
                user:user,

            }

            const res = await api.post("apiIgreja/pat/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("Patrimonios")

        } 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(`apiIgreja/pat/listar_id.php?id=${id_reg}`);

                setNome(res.data.dados.nome);
                setDescricao(res.data.dados.descricao);
                setCodigo(res.data.dados.codigo);
                setValor(res.data.dados.valor);
                setAtivo(res.data.dados.ativo);
                setObs(res.data.dados.obs);
                setEntrada(res.data.dados.entrada);
                setDoador(res.data.dados.doador);
                setDataCad(new Date(res.data.dados.dataCad + 'T06:00'));

                setImage(url + 'sistema/img/patrimonios/' + res.data.dados.tumb);

                setEdit(false);

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



    useEffect(() => {
        loadData()
            .then(() => setLoading(false))

    }, [])

    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}>Código do Item</Text>

                    <TextInput
                        placeholder="Código do Item"
                        onChangeText={(text) => setCodigo(text)}
                        value={codigo}
                        style={styles.TextInput}
                    />
                </View>

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

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


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

                    <TextInput
                        placeholder="Nome Item"
                        onChangeText={(text) => setDescricao(text)}
                        value={descricao}
                        style={styles.TextInputMulti}
                        maxLength={255}
                        multiline={true}
                    />
                </View>



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


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

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

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


                    <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}>Compra / Doação</Text>
                        <View style={styles.TextInput}>
                            <Picker
                                selectedValue={ativo}
                                onValueChange={(itemValue, itemIndex) => setEntrada(itemValue)}
                                style={{ color: '#000' }}
                            >
                                <Picker.Item label="Compra" value="Compra" />
                                <Picker.Item label="Doação" value="Doação" />

                            </Picker>
                        </View>

                    </View>

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

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

                    
                </View>



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

                        <TextInput
                            placeholder="Nome do Doador"
                            onChangeText={(text) => setDoador(text)}
                            value={doador}
                            style={styles.TextInput}
                        />
                    </View>



                    <View>
                    <Text style={styles.TitleInputs}>Observações</Text>

                    <TextInput
                        placeholder="Observações do Item"
                        onChangeText={(text) => setObs(text)}
                        value={obs}
                        style={styles.TextInputMulti}
                        maxLength={255}
                        multiline={true}
                    />
                </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 NovoRegistro;