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 [titulo, setTitulo] = useState("");
    const [descricao, setDescricao] = useState("");
   
    const [dataTar, setdataTar] = useState(new Date());
    const [show, setShow] = useState(false);

    const [hora, setHora] = useState(new Date());
    const [show2, setShow2] = useState(false);

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

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

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

    
    async function saveData() {       

        const id_igreja: any = await AsyncStorage.getItem('@id_igreja');
        const dataTarF = format(dataTar, 'yyyy-MM-dd');
        const horaF = format(hora, 'HH:mm');
       
        if (titulo == "" || descricao == "") {
            showMessage({
                message: "Erro ao Salvar",
                description: 'Preencha os Campos Obrigatórios!',
                type: "warning",
            });
            return;
        }



        try {
            const obj = {
                id: id_reg,
                titulo: titulo,
                descricao: descricao,                
                dataTar: dataTarF,
                hora: horaF,               
                igreja: id_igreja.replace(/['"]+/g, ''),
                
            }

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

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

                setTitulo(res.data.dados.titulo);
                setDescricao(res.data.dados.descricao);               
                setdataTar(new Date(res.data.dados.dataTar + 'T06:00'));
                setHora(new Date(res.data.dados.horaDate));
                                
                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}>Título <Text style={{fontSize:13}}>(25 Caracteres)</Text></Text>

                    <TextInput
                        placeholder="Título da Tarefa"
                        onChangeText={(text) => setTitulo(text)}
                        value={titulo}
                        style={styles.TextInput}
                        maxLength={25}
                    />
                </View>

                <View>
                    <Text style={styles.TitleInputs}> Descrição <Text style={{fontSize:13}}> (75 Caracteres)</Text></Text>

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

                


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


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

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

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


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

                        <TouchableOpacity
                            style={styles.pickDate}
                            onPress={() => setShow2(true)}
                        >
                            <Text style={styles.date}>{format(hora, 'HH:mm')}</Text>
                              
                            <AntDesign style={{ alignSelf: 'center', marginLeft: 25, }} name="caretdown" size={10} color="gray" />
                        </TouchableOpacity>
                    </View>

                    {show2 && (
                        <DateTimePicker
                            testID="dateTimePicker"
                            value={hora}
                            mode="time"
                            is24Hour={true}
                            display="clock"
                            onChange={onChange2}
                        />
                    )}


                </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;