import React, { useState, useEffect } from "react";
import {
  SafeAreaView,
  View,
  Text,
  TextInput,
  ScrollView,
  TouchableOpacity,
  Image,
  Alert
} from 'react-native';
import * as Constantes from '../Constantes/Servidor'
import AsyncStorage from '@react-native-async-storage/async-storage';

import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import Ionicons from 'react-native-vector-icons/Ionicons';

import CustomButton from '../components/CustomButton';

const LoginScreen = ({navigation}) => {
const [email, setEmail] = useState('');
const [clave, setClave] = useState('');

async function Login(){
  let data = new FormData();
  data.append('email', email);
  data.append('clave', clave);
  let res = await fetch(
    Constantes.url_apiRemota+'loginUsuario.php',
    {
    method: 'post',
    body: data,
    headers: {
    Accept:"application/x-www-form-urlencoded",
    },
    }
  );
  let responseJson = await res.json();
  if(responseJson == "0 results"){
    Alert.alert(
      "AAAOrange",
      "El correo o contraseña es incorrecta o el usuario no esta registrado",
      [
        { text: "OK", onPress: () => {}}
      ]
    )
  }else{
    //alert( JSON.stringify(responseJson))
    await AsyncStorage.setItem(
      'datos',
      JSON.stringify(responseJson)
    )
    navigation.navigate('Home')
  }
}

async function comprobarLogin(){
  try {
    const value = await AsyncStorage.getItem('datos');
    if (value !== null) {
      // We have data!!
      console.log(value);
      navigation.navigate('Home')
    }
  } catch (error) {
    // Error retrieving data
  }
};

useEffect(() => {
 comprobarLogin()
}, [])


  return (
    <SafeAreaView style={{flex: 1, justifyContent: 'center' }}>
      <ScrollView>
      <View style={{paddingHorizontal: 25}}>
        <View style={{alignItems: 'center'}}>
        <Image
          source={require('../assets/images/misc/logo.jpeg')}
          style={{
            transform: [{rotate: '0deg'}],
            width:300,
            height:300
          }}
        />
        </View>

        <Text
          style={{
            fontFamily: 'Roboto-Medium',
            fontSize: 28,
            fontWeight: '500',
            color: '#333',
            marginBottom: 30,
          }}>
          Login
        </Text>

        <View
        style={{
        flexDirection: 'row',
        borderBottomColor: '#ccc',
        borderBottomWidth: 1,
        paddingBottom: 8,
        marginBottom: 25
        }}
       >
        <MaterialIcons
              name="alternate-email"
              size={20}
              color="#666"
              style={{marginRight: 5}}
            />
        <TextInput
          placeholder='Email'
          style={{flex: 1, paddingVertical: 0}}
          keyboardType="email-address"
          onChangeText={(text)=> setEmail(text) }
        />
      </View>

      <View
        style={{
        flexDirection: 'row',
        borderBottomColor: '#ccc',
        borderBottomWidth: 1,
        paddingBottom: 8,
        marginBottom: 25
        }}
       >
        <Ionicons
              name="ios-lock-closed-outline"
              size={20}
              color="#666"
              style={{marginRight: 5}}
            />
        <TextInput
          placeholder='Clave'
          style={{flex: 1, paddingVertical: 0}}
          secureTextEntry={true}
          onChangeText={(text)=> setClave(text) }
        />
      </View>

        
        <CustomButton label={"Login"} onPress={() => Login()} />

        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'center',
            marginBottom: 30,
          }}>
          <Text>Eres nuevo en la app?</Text>
          <TouchableOpacity onPress={() => navigation.navigate('Register')}>
            <Text style={{color: '#AD40AF', fontWeight: '700'}}> Registrate</Text>
          </TouchableOpacity>
        </View>
      </View>
      </ScrollView>
    </SafeAreaView>
  );
};

export default LoginScreen;