import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

import { FirebaseAuth as firestore } from '../../hoc/Firestore'

import FieldGroup from '../Form/FieldGroup'

const mapStateToProps = (state) => {
  return {
    login: state.login.login
  }
}

class LoginForm extends Component {
  constructor () {
    super()
    this.state = {
      errorEmail: false,
      errorPassword: false,
      errorMessage: '',
      name: '',
      password: ''
    }
  }

  validateForm = () => {
    let states = { errorEmail: false, errorPassword: false }

    if (!this.state.email) {
      states.errorEmail = true
    }

    if (!this.state.password) {
      states.errorPassword = true
    }

    this.setState(states)

    // no errors
    if (states.errorEmail === false && states.errorPassword === false) {
      return true
    }
    return false
  }

  handleChange = (a) => {
    this.setState(a)
  }

  handleSubmit = (e) => {
    e.preventDefault()

    if (!this.validateForm()) {
      return false
    }

    firestore.signInWithEmailAndPassword(this.state.email, this.state.password).then(() => {
      this.props.history.push('/admin')
    }).catch((error) => {
      // Handle Errors here.
      this.setState({
        errorMessage: error.message
      })
    })
  }

  render () {
    return (
      <form className='rd-mailform text-left' data-form-output='form-output-global' data-form-type='login' onSubmit={this.handleSubmit}>
        <div className={(this.state.errorMessage) ? 'alert alert-danger' : ''} role='alert'>{(this.state.errorMessage) ? this.state.errorMessage : ''}</div>
        <FieldGroup
          id='email'
          type='text'
          label='Username'
          placeholder='Username'
          autocomplete='username email'
          value={this.state.email}
          pushChangeParent={this.handleChange}
          required={true}
        />
        <FieldGroup
          id='password'
          type='password'
          label='Password'
          placeholder='Password'
          autocomplete='user password'
          value={this.state.password}
          pushChangeParent={this.handleChange}
          required={true}
        />
        <button className='btn btn-primary btn-block btn-sm offset-top-22' type='submit'>Login</button>
      </form>
    )
  }
}

LoginForm.propTypes = {
  history: PropTypes.object,
}

export default connect(mapStateToProps)(LoginForm)
