import React, { useState, useEffect } from 'react';
import {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 api from '../../services/api';

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


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

    const route = useRoute<RouteProp<ParamList, 'Detail'>>();
    const id_reg = route?.params?.id_reg;
    const id_usu = route?.params?.id_usu;
       
    const [titulo, setTitulo] = useState("");
    const [descricao, setDescricao] = useState("");
    const [obs, setObs] = 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 user = await AsyncStorage.getItem('@user');     
        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,       
                obs: obs,
                user: user,
                idUsu: id_usu,
            }

            const res = await api.post("api/tarefas/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("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(`api/tarefas/listar_id.php?id=${id_reg}`);               
                
                setTitulo(res.data.dados.titulo);
                setDescricao(res.data.dados.descricao);               
                setdataTar(new Date(res.data.dados.data + 'T06:00'));
                setHora(new Date(res.data.dados.hora));                
                setObs(res.data.dados.obs);                
               
                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 <Success />
    }
    

    return (
        <View style={{ flex: 1, marginTop: 20 }}>
            <View style={styles.Header}>
                <TouchableOpacity
                    style={styles.BackButton}
                    onPress={() => navigation.push("Tarefas")}
                >
                    <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="default"
                            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="default"
                            onChange={onChange2}
                        />
                    )}


                </View>
           


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

                    <TextInput
                        placeholder="Observações"
                        onChangeText={(text) => setObs(text)}
                        value={obs}
                        style={styles.TextInputArea}
                        multiline={true}
                        numberOfLines={6}
                    />
                </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;