import React from "react";
import { useState } from "react";
import { View, TextInput, Text, StyleSheet } from "react-native";
import Button from "../components/Buttons/Button";
import { login } from "../thunks/user.thunk";
import { useDispatch } from "react-redux";

export const LogIn = () => {

  const [username, setUsername] = useState()
  const [password, setPassword] = useState()
  const [error, setError] = useState()
  const dispatch = useDispatch();

  const loginHandler = () => {
    dispatch(
      login(username, password, function (result) {
        console.log(result.data)
        if (!result.OK) {
          setUsername("");
          setPassword("");
          setError(result.data.Message ? result.data.Message : "Error occurred during Login,please try again!");
        }
      })
    )
  }

  return (
    <View style={{flex: 1, justifyContent: 'center'}}>
      <Text style={styles.errorMessage}>{error && error}</Text>
      <TextInput focus={true}
        style={styles.input}
        placeholder='Username'
        placeholderTextColor='#000' 
        value={username} 
        onChangeText={setUsername} 
        />
      <TextInput focus={true}
        style={styles.input}
        placeholder='Password'
        placeholderTextColor='#000'
        value={password}
        onChangeText={setPassword}
        secureTextEntry />
      <Button 
        onPress={loginHandler} 
        title='Log In' 
        style={{ margin: 12, backgroundColor: '#3E5076' }} 
        />
    </View>
  )
}

const styles = StyleSheet.create({
  input: {
    height: 40,
    margin: 12,
    borderWidth: 1,
    padding: 10,
    borderRadius: 5
  },
  errorMessage: {
    color: 'red',
    margin: 12
  }
});