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 [nome, setNome] = useState("");
    const [celular, setCelular] = useState("");
    const [endereco, setEndereco] = useState("");
    const [email, setEmail] = useState("");   
    const [cargo, setCargo] = useState("");
    const [cpf, setCPF] = useState("");
    const [obs, setObs] = useState("");
    const [salario, setSalario] = useState("");
    const [hora, setHora] = useState("");
    const [horaEntrada, setHoraEntrada] = useState("");
    const [horaSaida, setHoraSaida] = useState("");
    const [jornada, setJornada] = useState("");

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

    async function selectListaCargo() {           
        try {
            const response = await api.get(`api/funcionarios/listar_cargos.php`);
            setListaCargo(response.data.resultado);
        } catch (error) {
            console.log(error);
        }
    }
   

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

    const onChange = async (event: any, selectedDate: any) => {
        const currentDate = selectedDate || dataNasc;
        setShow(Platform.OS === 'ios');
        setdataNasc(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/funcionarios/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/funcionarios/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 dataNascF = format(dataNasc, 'yyyy-MM-dd');  
        
        if (nome == "" || cpf == "" || email == "") {
            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,
                cargo: cargo,
                foto: nomeImagem,
                cpf: cpf,
                data_nasc: dataNascF,
                obs: obs,
                salario: salario,
                hora: hora,
                horaEntrada: horaEntrada,
                horaSaida: horaSaida,
                jornada: jornada,
                user: user,
                
            }

            const res = await api.post("api/funcionarios/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("Funcionarios")

        } 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/funcionarios/listar_id.php?id=${id_reg}`);
                                 
               
                setNome(res.data.dados.nome);
                setCelular(res.data.dados.telefone);
                setEndereco(res.data.dados.endereco);
                setEmail(res.data.dados.email);
                setCargo(res.data.dados.cargo);
                setCPF(res.data.dados.cpf);
                setdataNasc(new Date(res.data.dados.data_nasc + 'T06:00'));
                setObs(res.data.dados.obs);
                setSalario(res.data.dados.salario);
                setHora(res.data.dados.hora);
                setHoraEntrada(res.data.dados.horaEntrada);
                setHoraSaida(res.data.dados.horaSaida);
                setJornada(res.data.dados.jornada);
                setImage(url + 'painel/images/perfil/' + res.data.dados.foto);   
               
                setEdit(false);
                
            } else {
                setEdit(true);
            }
        } catch (error) {
            console.log('Error ao carregar os Dados');
        }
    }

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

    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("Funcionarios")}
                >
                    <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>
                    <Text style={styles.TitleInputs}>Cargo</Text>
                    <View style={styles.Picker}>
                        <Picker
                            selectedValue={cargo}
                            onValueChange={(itemValue, itemIndex) => setCargo(itemValue)}
                            style={{ color: '#000' }}
                        >
                            {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}>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="default"
                            onChange={onChange}
                            
                        />
                    )}




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

            
            </View>

            </View>




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

            
                <Text style={styles.TitleInputs}>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}>Jornada</Text>

                        <TextInputMask
                    style={styles.TextInput}
                    type={'datetime'}
                    options={{
                        maskType: 'BRL',
                        format:'HH:mm'
                        
                    }}
                    value={jornada}
                    onChangeText={text => setJornada(text)}
                    
                />
                    </View>

                   

            </View>






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

                <TextInput
                    placeholder="R$ Valor Mensal"
                    onChangeText={(text) => setSalario(text)}
                    value={salario}
                    style={styles.TextInput}
                />
            </View> 
                       
                    </View>

                   

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

                <TextInput
                    placeholder="R$ Hora"
                    onChangeText={(text) => setHora(text)}
                    value={hora}
                    style={styles.TextInput}
                />
            </View> 
                    </View>

                   

            </View>





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

                        <TextInputMask
                    style={styles.TextInput}
                    type={'datetime'}
                    options={{
                        maskType: 'BRL',
                        format:'HH:mm'
                        
                    }}
                    value={horaEntrada}
                    onChangeText={text => setHoraEntrada(text)}
                    
                />
                    </View>


                   

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

                        <TextInputMask
                    style={styles.TextInput}
                    type={'datetime'}
                    options={{
                        maskType: 'BRL',
                        format:'HH:mm'
                        
                    }}
                    value={horaSaida}
                    onChangeText={text => setHoraSaida(text)}
                    
                />
                    </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}>Observações</Text>

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