import React, { useState } from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';
import { TextInput, Button, HelperText } from 'react-native-paper';
import API from './../API.js';
import { useNavigation } from '@react-navigation/native';
import i18n from "../i18nMessages.js";


let RegisterForm = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [password2, setPassword2] = useState('');
  const navigation = useNavigation();
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [description, setDescription] = useState('');
  const [emailValidated, setEmailValidated] = useState(false);

  const validateEmail = async () => {
    if (!email) return;
    API.getInvitation(email)
      .then(data => {
        //console.log(data);
        if (data && data.status && data.status === 'ok') setEmailValidated(true);
        else alert(data.status);
      }).catch(console.log);
  }

  const registerUser = async () => {
    if (!password || (password != password2))
      return alert("Passwords do not match!");
    if (!firstName || !lastName)
      return alert("Please enter your name!");
    if (!description)
      return alert("Please enter a description!");
    await API.signup(email, password, email, {
      firstName,
      lastName,
      description
    })
      .then(data => {
        console.log('registerData:', data);
        if (data && data.status && data.status === 'ok') {
          return navigation.reset({
            index: 0,
            routes: [{ name: 'MainNavigation' }],
          });
        }
      }).catch( (error) => {
        console.error("error at registering", error);
      });
  }

  const registrationData = (
    <>
      <TextInput
        style={styles.input}
        onChangeText={text => setPassword(text)}
        defaultValue={password}
        placeholder="password"
        textContentType="password"
        label={i18n.t("message.password")}
        secureTextEntry={true}
        autoCapitalize='none'
        autoComplete='email'
        autoCorrect={false}
        mode="outlined"
      />
      <TextInput
        style={styles.input}
        onChangeText={text => setPassword2(text)}
        defaultValue={password}
        placeholder="same password"
        textContentType="same password"
        label={i18n.t("message.rpassword")}
        secureTextEntry={true}
        autoCapitalize='none'
        autoComplete='email'
        autoCorrect={false}
        mode="outlined"
      />
      <TextInput
        style={styles.input}
        onChangeText={text => setFirstName(text)}
        defaultValue={firstName}
        placeholder="First Name"
        label={i18n.t("message.name")}
        autoCapitalize='words'
        autoComplete='name'
        mode="outlined"
        keyboardType='default'
      />
      <TextInput
        style={styles.input}
        onChangeText={text => setLastName(text)}
        defaultValue={lastName}
        placeholder="Last Name"
        label={i18n.t("message.lastName")}
        autoCapitalize='words'
        autoComplete='name'
        mode="outlined"
        keyboardType='default'
      />
      <TextInput
        style={styles.input}
        onChangeText={text => setDescription(text)}
        defaultValue={description}
        placeholder="Description so others can know you"
        label={i18n.t("message.describeYourself")}
        autoCapitalize='sentences'
        autoComplete='description'
        mode="outlined"
        keyboardType='default'
      />
    </>
  );

  return (
    <View style={styles.mainView}>
      <TextInput
        style={styles.input}
        onChangeText={text => setEmail(text)}
        defaultValue={email}
        placeholder="email"
        label={i18n.t("message.email")}
        autoCapitalize='none'
        autoComplete='email'
        autoCorrect={false}
        mode="outlined"
        keyboardType='email-address'
        disabled={emailValidated}
      />
      {emailValidated ? registrationData : <></>}
      <View style={{ flexDirection: "row" }}>
        <Button
          style={styles.button}
          onPress={async () => {
            if (emailValidated) registerUser();
            else validateEmail();
          }}
        >
          {i18n.t("message.submit")}
        </Button>
      </View>
    </View>
  );
}

export default RegisterForm;

const styles = StyleSheet.create({
  mainView: {
    width: "100%",
    alignContent: 'center',
    alignItems: 'center',
  },
  input: {
    backgroundColor: 'white',
    width: "80%"
  },
  button: {
    marginTop: 10,

  }
});