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/1item';
import api from '../../../services/api';
import url from '../../../services/url';
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;
        valor: string;
        corretor: string;
        comprador: string;
        vendedor: string;
        comissao_corretor: string;
        comissao_imob: string;
        data_inicio: string;
        data_final: string;
        classe_linha: string;
        id_imovel: string;
        titulo_imovel: string;
        img_imovel: string;
    }
}


const CardUsuarios = ({ data }: DadosProps) => {

    const [abrirModal, setAbrirModal] = useState(false);
    const navigation: any = useNavigation();

    const [id, setId] = useState("");
    const [nome, setNome] = 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/arquivos/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/arquivos/upload.php", formData);


    };

    

    async function arquivo(nome:string, id:string) {       
        
        setAbrirModalArquivo(true);
        setId(id); 
        setNome(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: id,
                nomeArquivo: nomeArquivo,
                nomeImagem: nomeImagem,
                user: user,
                registro: 'Imóveis',
            }

            const res = await api.post("api/arquivos/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 ?

                <Text style={{ color: '#595858', fontSize: 14, marginTop: 10, alignContent: "center", textAlign: "center" }}>Nenhum Registro Encontrado!</Text>

                :

                <View>
                    <SwipeableRow

                        onPressArquivo={async () => {
                            arquivo(data.valor, data.id_imovel);
                        }}


                    >
                        <TouchableOpacity
                            style={styles.box}
                            onPress={() => setAbrirModal(true)}
                        >

                            <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', marginTop: -5 }}>
                                <View style={{ width: '100%', marginTop: 3 }}>
                                    <Text style={{ color: data.classe_linha, fontSize: 15, fontWeight:'bold'}}>R$ {data.valor} - <Text style={{ color: '#000', fontSize: 12 }}>Corretor: {data.corretor}</Text></Text>
                                    <Text style={{ color: '#000', fontSize: 12 }}>Inquilino: {data.comprador} / Proprietário: {data.vendedor}</Text>
                                    <Text style={{ color: '#000', fontSize: 12 }}>Comissão Corretor: R$ {data.comissao_corretor} / Comissão Imob: R${data.comissao_imob}</Text>
                                </View>
                            </View>


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


                        <View style={styles.Section}>
                            <Text style={styles.Cliente}>Imóvel: {data.titulo_imovel} </Text>
                        </View>

                        <View style={styles.Section}>
                            <Text style={styles.Cliente}>Valor: R$ {data.valor} </Text>
                        </View>



                        <View style={styles.Section}>
                            <Text style={styles.Entrada}>Corretor: {data.corretor}</Text>

                        </View>

                        <View style={styles.Section}>
                            <Text style={styles.Entrada}>Inquilino: {data.comprador}</Text>

                        </View>

                        <View style={styles.Section}>
                            <Text style={styles.Entrada}>Proprietário: {data.vendedor}</Text>

                        </View>


                        <View style={styles.Section}>
                            <Text style={styles.Entrada}>Comissão Imobiliária: R$ {data.comissao_imob}</Text>

                        </View>


                        <View style={styles.Section}>
                            <Text style={styles.Entrada}>Comissão Corretor: R$ {data.comissao_corretor}</Text>

                        </View>


                        <View style={styles.Section}>
                            <Text style={styles.Entrada}>Data Início: {data.data_inicio}</Text>

                        </View>


                        <View style={styles.Section}>
                            <Text style={styles.Entrada}>Data Final: {data.data_final}</Text>

                        </View>


                        <View style={styles.viewImg}>
                                            <Image style={styles.ImagemModal} source={{ uri: (url + 'sistema/painel/images/imoveis/' + data.img_imovel) }} />
                                           
                                        </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}>Comprador: {nome}</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 CardUsuarios;