import { useNavigation } from '@react-navigation/native';
import React, { useState, useEffect } from 'react';
import {Image, TextInput, AsyncStorage, Modal, Alert, Linking, Text, TouchableOpacity, View } from 'react-native';
import SwipeableRow from '../../Linhas/Clientes';
import api from '../../../services/api';
import { styles } from './styles';
import { showMessage, hideMessage } from "react-native-flash-message";
import { EvilIcons, MaterialIcons, AntDesign, Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';

interface DadosProps {
    data: {
        id: string;
        nome: string;
        telefone: string;
        ativo: string;
        endereco: string;
        pessoa: string;
        doc: string;
        data_cadF: string;
        data_nascF: string;
        obs: string;
        email:string;
    }
}


const CardClientes = ({ data }: DadosProps) => {
    const navigation: any = useNavigation();
    const [abrirModal, setAbrirModal] = useState(false);
    const [idCliente, setIdCliente] = useState("");
    const [nomeCliente, setNomeCliente] = useState("");
    const [abrirModalArquivo, setAbrirModalArquivo] = useState(false);
    const [nomeArquivo, setNomeArquivo] = useState("");

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


    };

    async function excluir(nome:string, id:string) {
        const user = await AsyncStorage.getItem('@user'); 
        Alert.alert('Sair', `Você tem certeza que deseja excluir o Registro : ` + nome, [
            {
                text: 'Não',
                style: 'cancel',
            },

            {
                text: 'Sim',
                onPress: async () => {
                    try {
                        const response = await api.get(`api/fornecedores/excluir.php?id=${id}&user=${user}&nome=${nome}`);

                        showMessage({
                            message: "Excluído Sucesso",
                            description: "Registro Excluído",
                            type: "info",
                            duration: 800,
                        });

                        navigation.push('Fornecedores');
                    } catch (error) {
                        Alert.alert('Não foi possivel excluir, tente novamente!')
                    }
                }
            }
        ])
    }


    async function arquivo(nome:string, id:string) {
        
        const user = await AsyncStorage.getItem('@user'); 
        setAbrirModalArquivo(true);
        setIdCliente(id); 
        setNomeCliente(nome);    
    }

    async function salvarArquivo() {
        const user = await AsyncStorage.getItem('@user');     
        
        if (nomeArquivo == "" || image == "") {
            showMessage({
                message: "Erro ao Salvar",
                description: 'Preencha o Nome e insira uma Foto!',
                type: "warning",
            });
            return;
        }

        try {
            const obj = {
                id: idCliente,
                nomeArquivo: nomeArquivo,
                nomeImagem: nomeImagem,
                user: user,
                
            }

            const res = await api.post("api/fornecedores/salvar-arquivo.php", obj);

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

                return;
            }

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

            setAbrirModalArquivo(false);
            setNomeArquivo("");
            setNomeImagem("");
            setImage(null);
           

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

        
          
    }

    return (
        <>
            {data.id === undefined && data.nome === undefined ?
               
               <Text style={{ color: '#595858', fontSize: 14, marginTop:10, alignContent:"center", textAlign:"center" }}>Nenhum Registro Encontrado!</Text>
                
                :

                <View>
                    <SwipeableRow
                        onPressWhatsapp={async () => {
                            await Linking.openURL(`http://api.whatsapp.com/send?1=pt_BR&phone=55${data.telefone}`)
                        }}

                        onPressEdit={async () => {
                            navigation.push('NovoFornecedor', { id_reg: data.id });
                        }}

                        onPressDelete={async () => {
                            excluir(data.nome, data.id);
                        }}

                        onPressArquivo={async () => {
                            arquivo(data.nome, data.id);
                        }}
                    >
                        <TouchableOpacity
                            style={styles.box}
                            onPress={() => setAbrirModal(true)}
                        >
                             {(() => {
                                 if (data.ativo == 'Sim') { 
                                     return(
                                        <Text style={{ color: '#000' }}>{data.nome} - Telefone: {data.telefone}</Text>
                                     )                                   
                            
                                 }else{
                                    return(
                                        <Text style={{ color: '#bfbfbf' }}>{data.nome} - Telefone: {data.telefone}</Text>
                                     ) 
                                 }
                                })()}

                        </TouchableOpacity>
                    </SwipeableRow>
                </View>
            }



<Modal 
        visible={abrirModal}
        animationType={'fade'}
        transparent={true}
        onRequestClose={() => {
          setAbrirModal(!abrirModal)
        }}
      >
          <View style={styles.centralizarModal}>
         <View style={styles.CardContainerModal}>
         <TouchableOpacity
              style={styles.removeItem}
              onPress={() => setAbrirModal(false)}
            >
              <EvilIcons name="close" size={25} color="black" />
            </TouchableOpacity>
         <Text style={styles.Cliente}>{data.nome}</Text>
                

                <View style={styles.Section}>
                    <MaterialIcons style={styles.Icon} name="contact-phone" size={22} color="#c1c1c1" />
                    <Text style={styles.Entrada}>{data.telefone}</Text>
                    <Text style={styles.Vencimento}>Documento: {data.doc}</Text>
                </View>

                

                <View style={styles.Section}>
                    <MaterialIcons style={styles.Icon} name="date-range" size={22} color="#c1c1c1" />
                    <Text style={styles.Entrada}>Cadastro: {data.data_cadF}</Text>
                    {(() => {
                                 if (data.data_nascF != '00/00/0000') { 
                                     return(
                    <Text style={styles.Vencimento}>Nascimento: {data.data_nascF}</Text>
                                     )
                                 }
                    })()}                   
                </View>

               
                <View style={styles.Section}>
                    <MaterialIcons style={styles.Icon} name="mail" size={22} color="#c1c1c1" />
                    <Text style={styles.Entrada}>Email: {data.email}</Text>
                    
                </View>

                <View style={styles.Section}>
                    <MaterialIcons style={styles.Icon} name="location-city" size={22} color="#c1c1c1" />
                    <Text style={styles.Entrada}>Endereço: {data.endereco}</Text>
                    
                </View> 

                 <View style={styles.Section}>
                    <MaterialIcons style={styles.Icon} name="info-outline" size={22} color="#c1c1c1" />
                    <Text style={styles.Entrada}>OBS: {data.obs}</Text>
                    
                </View>                              

             </View>
             </View>
          </Modal>




          
<Modal 
        visible={abrirModalArquivo}
        animationType={'fade'}
        transparent={true}
        onRequestClose={() => {
          setAbrirModalArquivo(!abrirModalArquivo)
        }}
      >
          <View style={styles.centralizarModal}>
         <View style={styles.CardContainerModal}>
         <TouchableOpacity
              style={styles.removeItem}
              onPress={() => setAbrirModalArquivo(false)}
            >
              <EvilIcons name="close" size={25} color="black" />
            </TouchableOpacity>
         <Text style={styles.Cliente}>Fornecedor: {nomeCliente}</Text>
                
         <View>
                
                <TextInput
                    placeholder="Nome Arquivo*"
                    onChangeText={(text) => setNomeArquivo(text)}
                    value={nomeArquivo}
                    style={styles.TextInput}
                />

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

                <TouchableOpacity
                    style={styles.Button}
                    onPress={() => {                        
                        salvarArquivo();
                    }}
                >
                    <Text style={styles.ButtonText}>Inserir Arquivo</Text>
                </TouchableOpacity>
                                           

             </View>
             </View>
          </Modal>


        </>
    );
}

export default CardClientes;