import React, {useState} from 'react';
import {
  SafeAreaView,
  ScrollView,
  View,
  Text,
  TextInput,
  TouchableOpacity,
  Image,
  Alert
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import BouncyCheckbox from "react-native-bouncy-checkbox";
import DatePicker from 'react-native-date-picker';
import CheckBox from '@react-native-community/checkbox';

import InputField from '../components/InputField';

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

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

import * as Constantes from '../Constantes/Servidor'

const RegisterScreen = ({navigation}) => {
  const [date, setDate] = useState(new Date());
  const [open, setOpen] = useState(false);
  const [dobLabel, setDobLabel] = useState('Date of Birth');

  const [checkboxState, setCheckboxState] = useState(true);
  const [checkboxStateJuridica, setCheckboxStateJuridica] = useState(false);
  const [nombres, setNombres] = useState('');
  const [apellidos, setApellidos] = useState('');
  const [direccion, setDireccion] = useState('');
  const [email, setEmail] = useState('');
  const [telefono, setTelefono] = useState('');
  const [ciudad, setCiudad] = useState('');
  const [razon_social, setRazon_social] = useState('');
  const [nit, setNit] = useState('');
  const [clave, setClave] = useState('');

  async function Registrar(){
    if (email === ''){
     Alert.alert('Ingresa un correo valido')
    }else{
    let data = new FormData();
    if(checkboxState == true){
      data.append('tipo_persona', 'Persona Natural');
    }else{
      data.append('tipo_persona', 'Persona Juridica');
    }
    data.append('nombres', nombres);
    data.append('apellidos', apellidos);
    data.append('direccion', direccion);
    data.append('email', email);
    data.append('telefono', telefono);
    data.append('ciudad', ciudad);
    data.append('razon_social', razon_social);
    data.append('nit', nit);
    data.append('clave', clave);

    let res = await fetch(
      Constantes.url_apiRemota+'guardarUsuario',
      {
      method: 'post',
      body: data,
      headers: {
      Accept:"application/x-www-form-urlencoded",
      },
      }
    );
    let responseJson = await res.json();
    alert(responseJson)
    if(responseJson == "falta datos"){
      Alert.alert('Falta datos');
    }else{
      Alert.alert(
        "AAAOrange",
        "Usuario creado",
        [
          { text: "OK", onPress: () => navigation.navigate('Login') }
        ]
      )
    }
   }
  }

  const validate = (text) => {
    const reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w\w+)+$/;
    console.log(text, reg.test(text));
    if(reg.test(text) === true){
      setEmail(text)
    }
  };
 

  return (
    <SafeAreaView style={{flex: 1, justifyContent: 'center'}}>
      <ScrollView
        showsVerticalScrollIndicator={false}
        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,
          }}>
          Registrar
        </Text>

        <Text style={{textAlign: 'center', color: '#666', marginBottom: 30}}>
          Ingresa todos los datos
        </Text>

      <View style={{ flexDirection:'row' }} >
        <BouncyCheckbox
        style={{ marginTop: 16 }}
        isChecked={checkboxState}
        text="Persona Natural"
        disableBuiltInState
        onPress={() => {
          setCheckboxState(true)
          setCheckboxStateJuridica(false) 
        }}
        />
        <Text>    </Text>
        <BouncyCheckbox
        style={{ marginTop: 16 }}
        isChecked={checkboxStateJuridica}
        text="Persona Juridica"
        disableBuiltInState
        onPress={() => {
          setCheckboxStateJuridica(true)
          setCheckboxState(false)
        }}
        />
      </View>
        <Text></Text>

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

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

      <View
        style={{
        flexDirection: 'row',
        borderBottomColor: '#ccc',
        borderBottomWidth: 1,
        paddingBottom: 8,
        marginBottom: 25
        }}
       >
        <Ionicons
              name="map-outline"
              size={20}
              color="#666"
              style={{marginRight: 5}}
            />
        <TextInput
          placeholder='Dirección'
          style={{flex: 1, paddingVertical: 0}}
          onChangeText={(text)=> setDireccion(text) }
        />
      </View>

      <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={validate}
        />
      </View>

      <View
        style={{
        flexDirection: 'row',
        borderBottomColor: '#ccc',
        borderBottomWidth: 1,
        paddingBottom: 8,
        marginBottom: 25
        }}
       >
        <Ionicons
              name="phone-portrait-outline"
              size={20}
              color="#666"
              style={{marginRight: 5}}
            />
        <TextInput
          placeholder='Teléfono'
          style={{flex: 1, paddingVertical: 0}}
          keyboardType='numeric'
          onChangeText={(text)=> setTelefono(text) }
        />
      </View>

      <View
        style={{
        flexDirection: 'row',
        borderBottomColor: '#ccc',
        borderBottomWidth: 1,
        paddingBottom: 8,
        marginBottom: 25
        }}
       >
        <Ionicons
              name="phone-portrait-outline"
              size={20}
              color="#666"
              style={{marginRight: 5}}
            />
        <TextInput
          placeholder='Nit'
          style={{flex: 1, paddingVertical: 0}}
          onChangeText={(text)=> setNit(text) }
        />
      </View>

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

      <View
        style={{
        flexDirection: 'row',
        borderBottomColor: '#ccc',
        borderBottomWidth: 1,
        paddingBottom: 8,
        marginBottom: 25
        }}
       >
        <Ionicons
              name="home-outline"
              size={20}
              color="#666"
              style={{marginRight: 5}}
            />
        <TextInput
          placeholder='Razón social'
          style={{flex: 1, paddingVertical: 0}}
          onChangeText={(text)=> setRazon_social(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>


        {/* <View
          style={{
            flexDirection: 'row',
            borderBottomColor: '#ccc',
            borderBottomWidth: 1,
            paddingBottom: 8,
            marginBottom: 30,
          }}>
          <Ionicons
            name="calendar-outline"
            size={20}
            color="#666"
            style={{marginRight: 5}}
          />
          <TouchableOpacity onPress={() => setOpen(true)}>
            <Text style={{color: '#666', marginLeft: 5, marginTop: 5}}>
              {dobLabel}
            </Text>
          </TouchableOpacity>
        </View>

        <DatePicker
          modal
          open={open}
          date={date}
          mode={'date'}
          maximumDate={new Date('2005-01-01')}
          minimumDate={new Date('1980-01-01')}
          onConfirm={date => {
            setOpen(false);
            setDate(date);
            setDobLabel(date.toDateString());
          }}
          onCancel={() => {
            setOpen(false);
          }}
        /> */}

        <CustomButton label={'Registrar'} onPress={() => Registrar()} />

        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'center',
            marginBottom: 30,
          }}>
          <Text>Ya estas registrado?</Text>
          <TouchableOpacity onPress={() => navigation.goBack()}>
            <Text style={{color: '#AD40AF', fontWeight: '700'}}> Login</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

export default RegisterScreen;