import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
  Alert,
  View,
  ActivityIndicator,
  Button,
  TextInput,
} from 'react-native';

import { emailChanged, passwordChanged, loginUser } from '../../actions';
import styles from './styles';

class Login extends Component {
  renderButtonOrSpinner() {
    if (this.props.loading) {
      return (
        <ActivityIndicator size="small" />
      );
    }
    return (
      <View style={styles.buttonView}>
        <Button
          title="Log In"
          onPress={() => this.props.loginUser({
            email: this.props.email,
            password: this.props.password,
          })}
        />
      </View>
    );
  }

  render() {
    if (this.props.error) {
      Alert.alert('Invalid password');
    }
    return (
      <View style={styles.view}>
        <TextInput
          onChangeText={text => this.props.emailChanged(text)}
          value={this.props.email}
          placeholder="Email"
        />
        <TextInput
          onChangeText={text => this.props.passwordChanged(text)}
          value={this.props.password}
          placeholder="Password"
          secureTextEntry
        />
        {this.renderButtonOrSpinner()}
      </View>
    );
  }
}

Login.propTypes = {
  loading: React.PropTypes.bool.isRequired,
  loginUser: React.PropTypes.func.isRequired,
  email: React.PropTypes.string.isRequired,
  emailChanged: React.PropTypes.func.isRequired,
  password: React.PropTypes.string.isRequired,
  passwordChanged: React.PropTypes.func.isRequired,
  error: React.PropTypes.string.isRequired,
};

Login.navigationOptions = {
  title: 'Login',
};

const mapStateToProps = ({ auth }) => auth;

const LoginScreen = connect(mapStateToProps, {
  emailChanged,
  passwordChanged,
  loginUser,
})(Login);

export default LoginScreen;
