import React, { useState } from 'react';
import { ImageBackground, StyleSheet, View, TouchableOpacity, TextInput, Dimensions, Alert, } from 'react-native';
import { ActivityIndicator, Text, } from 'react-native-paper'
import 'react-native-get-random-values';
import { Globals } from '../globals'
import { Controller, useForm } from 'react-hook-form';
import { authorize } from 'react-native-app-auth';

const Login = ({navigation}) => {
  const config = {
    issuer: 'http://10.0.2.2:8000',
    clientId: 'mobileapp',
    redirectUrl: 'mobile.clicknpush://oidc-callback',
    scopes: ['openid'],
    dangerouslyAllowUnsecureHttpRequests: true,
  };

  const [loading, setLoading] = useState(false);

  const { control, handleSubmit, formState: {errors} } = useForm({
    mode: 'all'
  });

  const login = async (credentials) => {
    setLoading(true);
    try {
      const result = await authorize(config); 
    } catch (error) {
      Alert.alert(error);
    }
    
    // try {
    //   const response = await axios({
    //     method: 'post',
    //     url: Globals.API_HOST + '/api/login/',
    //     timeout: 5000,
    //     data: formData,
    //   });
    //   resultMessage = response.statusText;
    // } catch (error) {
    //   resultMessage = error.toString();
    // }

    // dispatch({ type: "SUBMISSION_RECIEVED"});
    // navigation.navigate('RegisterResult', {result: resultMessage});
  }

  return(
    <ImageBackground style={styles.container} source={require('../assets/cover-dark.png')}>
      {!loading ? 
      <View>
        <View style={styles.brandContainer}>
          <Text style={styles.title} >Welcome back!</Text>
          <Text style={styles.subtitle} >Please enter your credentials.</Text>
        </View>
        <View style={styles.textContainer}>
          <Controller 
            control={control}
            render={({ field: { onChange, value }}) => (
              <TextInput 
                mode="outlined" 
                style={[styles.textInput, errors.identifier && styles.errorInput]} 
                placeholder="Username or email" 
                value={value}
                onChangeText={value => onChange(value)}
              ></TextInput>
            )}
            name="identifier"
            rules={{ required: true, }} />
          {errors.identifier?.type === "required" && <Text style={styles.errorText}>Username or password is required.</Text>}
          <Controller 
            control={control}
            render={({ field: { onChange, value }}) => (
              <TextInput 
                mode="outlined" 
                style={[styles.textInput, errors.password && styles.errorInput]} 
                placeholder="Password" 
                value={value}
                onChangeText={value => onChange(value)}
              ></TextInput>
            )}
            name="password"
            rules={{ required: true, }} />
          {errors.password?.type === "required" && <Text style={styles.errorText}>Password is required.</Text>}   
        </View>
        
        <View>
          <TouchableOpacity style={styles.loginBtn} onPress={handleSubmit(login)} >
              <Text style={{ color: 'white', fontSize: 20 }}>Login</Text>
          </TouchableOpacity>
          <Text style={styles.forgotPass}>Forgot password?</Text>
        </View>
      </View> : 
      <View style={styles.brandContainer}>
        <Text style={[{marginTop: 70, marginLeft: 20}, styles.title]} >Hold on while we sign you in.</Text>
        <ActivityIndicator style={{marginTop: 200}} size="large" animating={true} color="red"/>
      </View>}
    </ImageBackground>
  )
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
    flex: 1,
    flexDirection: 'column',
    resizeMode: 'cover',
  },

  brandContainer: {
      height: 100,
      marginVertical: 50,
      flexDirection: 'column',
      justifyContent: 'space-between'
  },

  title: {
    fontFamily: 'RacingSansOne-Regular',
    marginHorizontal: 25,
    marginTop: 30, 
    color: 'white',
    fontSize: 20
  },

  subtitle: {
    fontFamily: 'RacingSansOne-Regular',
    marginHorizontal: 25,
    marginTop: 30, 
    color: 'white',
    fontSize: 15
  },

  textContainer: { 
    marginHorizontal: 20,
    marginBottom: 30,
    borderRadius: 50,
  },

  textInput: {
    marginVertical: 7,
    paddingLeft: 30,
    borderRadius: 50,
    overflow: 'hidden',
    backgroundColor: 'white',
    height: 50
  },

  errorText: {
    alignSelf: 'flex-end',
    color: 'red',
    fontSize: 15
  },

  errorInput: {
    borderWidth: 2,
    borderColor: 'red'
  },

  loginBtn: {
    marginHorizontal: 20,
    borderRadius: 50,
    justifyContent: 'center',
    backgroundColor: '#df3f3f',
    margin: 5,
    height: 50,
    alignItems: 'center'
  },

  forgotPass: {
    marginTop: 20,
    color: 'white',
    alignSelf: 'center',
    margin: 5,
    height: 50,
  },

  btnContainer: {
    marginHorizontal: 20,
    borderRadius: 50,
    justifyContent: 'center',
    backgroundColor: '#df3f3f',
    margin: 5,
    height: 50,
    alignItems: 'center'
  },
})
 
export default Login;
 