import React, {useState, useEffect} from 'react';
import RNSInfo from 'react-native-sensitive-info';
import SInfo from 'react-native-sensitive-info';
import {
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  TouchableHighlight,
  TextInput,
  ScrollView,
} from 'react-native';
import {Icon} from 'react-native-elements';

const LoginUserScreen = ({navigation}) => {
  const [username, setUsername] = useState('');
  const [orgname, setOrgname] = useState('Org1');
  const [password, setPassword] = useState('');
  const [token, setToken] = useState('');
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  var [isPress, setIsPress] = useState(false);

  useEffect(() => {
    setError('');
  }, []);

  const setKey = async (key, value) => {
    return SInfo.setItem(key, value, {
      sharedPreferencesName: 'mySharedPrefs',
      keychainService: 'myKeychain',
    });
  };
  const getKey = async key => {
    return RNSInfo.getItem(key, {
      sharedPreferencesName: 'mySharedPrefs',
      keychainService: 'myKeychain',
    });
  };

  const login_user = async () => {
    var data = {
      username: username,
      orgName: orgname,
      args: [JSON.stringify({email: username, password: password})],
    };
    await fetch('http://192.168.29.141:4000/users/login', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
      .then(function (response) {
        //const cred = await Keychain.setGenericPassword(JSON.stringify(response));
        return response.json();
      })
      .then(async function (response_data) {
        console.log('\n response_data ', response_data);
        console.log('\nuser data success');
        if (response_data.token) {
          await setKey('token', response_data.token);
          setToken(response_data.token);
          var userobj = JSON.parse(response_data.user);
          setMessage('user ' + userobj.username + ' logged in');
          navigation.navigate('UserProfile', {user: userobj});
        } else {
          setMessage(response_data.msg);
        }
        var key_token = await getKey('token');
        console.log('retrived key_token ' + key_token);
      })
      .catch(error => {
        setError(error);
        console.log('error ' + error);
      });
  };

  var touchProps = {
    activeOpacity: 1,
    underlayColor: 'white',
    style: isPress ? styles.btnPress : styles.btnNormal,
    onHideUnderlay: () => setIsPress(false),
    onShowUnderlay: () => setIsPress(true),
    onPress: login_user,
  };

  var textInputProps = {
    style: styles.input,
    placeholderTextColor: '#4b4a4a',
  };
  var inputHeadingProps = {
    style: styles.inputHeading,
  };
  return (
    <>
      <StatusBar backgroundColor="#ffffff" barStyle="dark-content" />
      <View style={styles.viewRoot}>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'flex-start',
            alignItems: 'flex-start',
            marginTop: '-40%',
          }}>
          <TouchableHighlight
            onPress={() => navigation.goBack()}
            underlayColor="white"
            activeOpacity={0.5}>
            <Icon name="arrow-back" type="ionicon" size={36} color="#206ba5" />
          </TouchableHighlight>
        </View>
        <Text style={styles.heading}>Login</Text>
        <View style={{alignItems: 'center'}}>
          <View style={{flexDirection: 'column', marginTop: '10%'}}>
            <Text {...inputHeadingProps}>Username </Text>
            <TextInput
              {...textInputProps}
              keyboardDismissMode="none"
              defaultValue={username}
              placeholder="Name of the user"
              onChangeText={setUsername}
            />
          </View>
          <View style={{flexDirection: 'column', marginTop: '10%'}}>
            <Text {...inputHeadingProps}>Password</Text>
            <TextInput
              {...textInputProps}
              value={password}
              placeholder="enter the password"
              onChangeText={setPassword}
            />
          </View>

          <View
            style={{
              flexDirection: 'row',
              marginTop: '10%',
              justifyContent: 'center',
            }}>
            <TouchableHighlight {...touchProps}>
              <Text style={styles.btnText}>Submit</Text>
            </TouchableHighlight>
          </View>

          {message ? (
            <Text style={{color: '#206ba5', fontSize: 25}}>{message}</Text>
          ) : (
            <Text style={{color: 'red', fontSize: 25}}>{error.message}</Text>
          )}
          <View>
            <Text
              style={{color: '#206ba5', fontSize: 15, textAlign: 'left'}}
              onPress={() => navigation.navigate('RegisterUserScreen')}>
              Not a member yet?
            </Text>
          </View>
        </View>
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  viewRoot: {
    backgroundColor: '#ffffff',
    justifyContent: 'center',
    height: '100%',
  },
  heading: {
    color: '#1C254E',
    fontSize: 60,
    textAlign: 'center',
    fontFamily: 'Ubuntu-Bold',
  },

  icon: {
    alignSelf: 'flex-start',
    marginLeft: '28%',
    flexDirection: 'row',
  },
  btnNormal: {
    borderRadius: 10,
    height: 45,
    width: 140,
    backgroundColor: '#1C254E',
    alignItems: 'center',
    justifyContent: 'center',
  },
  btnText: {
    textAlign: 'center',
    fontSize: 22,
    color: 'white',
  },
  btnPress: {
    borderRadius: 10,
    height: 45,
    width: 140,
    backgroundColor: '#1C254E',
    justifyContent: 'center',
  },
  input: {
    height: 60,
    width: 280,
    margin: 12,
    borderRadius: 15,
    padding: 10,
    color: 'black',
    backgroundColor: '#c4c4c4',
  },
  inputHeading: {
    fontSize: 25,
    margin: 12,
    justifyContent: 'center',
    fontFamily: 'Ubuntu-Bold',
    color: '#1C254E',
  },
});

export default LoginUserScreen;
