import React, { Component } from 'react';
import {
  LayoutAnimation,
  StyleSheet,
  View,
} from 'react-native';
import { Button, ButtonGroup } from 'react-native-elements';
import { FormInput, FormLabel } from 'react-native-elements';
import { connect, Dispatch } from 'react-redux';
import { AuthActions } from '../../actions';
import { RootState, UserRole } from '../../models';
import { Colors } from '../ui';

interface OwnProps {
  role: UserRole;
  hasError: boolean;
  loading: boolean;
  setError: (error: string) => void;
}

interface DispatchProps {
  onLoginRequested: (email, password) => void;
  onSignupRequested: (email, password, name) => void;
}

type Props = OwnProps & DispatchProps;

interface State {
  email: string;
  password: string;
  name: string;
  newAccount: boolean;
}

class EmailLoginComponent extends Component<Props, State> {

  emailRef: any;
  passwordRef: any;

  state = {
    email: null,
    name: null,
    password: null,
    newAccount: false,
  };

  login() {
    const { email, password, name } = this.state;
    if (this.state.newAccount && (!name || name.length < 5)) {
      this.props.setError('Nazwa lub imię musi mieć przynajmniej 5 znaków');
      return;
    }
    if (this.state.newAccount) {
      this.props.onSignupRequested(email, password, name);
    } else {
      this.props.onLoginRequested(email, password);
    }
  }

  updateTab = (newAccount) => {
    this.setState({ newAccount });
    this.props.setError(null);
  }

  updateName = (name) => {
    this.setState({ name });
    this.props.setError(null);
  }

  updateEmail = (email) => {
    this.setState({ email });
    this.props.setError(null);
  }

  updatePassword = (password) => {
    this.setState({ password });
    this.props.setError(null);
  }

  componentDidUpdate() {
    LayoutAnimation.easeInEaseOut();
  }

  renderNameInput() {
    return this.state.newAccount && (
      <View>
        <FormLabel>
          Imię/Nazwa
        </FormLabel>
        <FormInput
          maxLength={100}
          placeholder='Nazwa/Imię i nazwisko'
          value={this.state.name}
          editable={!this.props.loading}
          onChangeText={(name) => this.updateName(name)}
          onEndEditing={() => this.emailRef.focus()}
        />
      </View>
    );
  }

  renderInputArea() {
    return (
      <View>
        {this.renderNameInput()}
        <FormLabel>
          Email
        </FormLabel>
        <FormInput
          ref={(ref) => { this.emailRef = ref; }}
          spellCheck={false}
          autoCorrect={false}
          keyboardType={'email-address'}
          autoCapitalize={'none'}
          placeholder='Email'
          value={this.state.email}
          editable={!this.props.loading}
          onChangeText={(email) => this.updateEmail(email)}
          onEndEditing={() => this.passwordRef.focus()}
        />
        <FormLabel>
          Hasło
        </FormLabel>
        <FormInput
          ref={(ref) => { this.passwordRef = ref; }}
          placeholder='Hasło'
          autoCapitalize={'none'}
          value={this.state.password}
          editable={!this.props.loading}
          secureTextEntry={true}
          onChangeText={(password) => this.updatePassword(password)}
        />
      </View>
    );
  }

  render() {
    const disabled = !!this.props.hasError
      || !this.state.email
      || !this.state.password
      || (this.state.newAccount && !this.state.name);
    const { loading, role } = this.props;
    return (
      <View style={styles.container}>
        <ButtonGroup
          onPress={(index) => this.updateTab(index === 1)}
          selectedIndex={this.state.newAccount ? 1 : 0}
          buttons={['Zaloguj się', 'Utwórz konto']}
          containerStyle={{ height: 45 }}
          selectedTextStyle={{ color: 'white' }}
          selectedButtonStyle={{
            backgroundColor: Colors[role === UserRole.EMPLOYEE ? 'employee' : 'employer'].primary,
          }}

        />
        {this.renderInputArea()}
        <Button
          disabled={disabled}
          backgroundColor={
            role === UserRole.EMPLOYEE
              ? Colors.employee.primary
              : Colors.employer.primary
          }
          title={loading ? '' : this.state.newAccount ? 'Utwórz konto' : 'Zaloguj się'}
          loading={loading}
          raised={!disabled}
          borderRadius={4}
          containerViewStyle={styles.button}
          fontWeight='bold'
          onPress={() => !loading && this.login()}
        />
      </View>
    );
  }
}

const mapDispatchToProps: (dispatch: Dispatch<RootState>, ownProps: OwnProps) => DispatchProps =
  (dispatch, ownProps) => ({
    onLoginRequested: (email, password) =>
      dispatch(AuthActions.loginWithEmailRequested(email, password, ownProps.role)),
    onSignupRequested: (email, password, name) =>
      dispatch(AuthActions.signupWithEmailRequested(name, email, password, ownProps.role)),
  });

export const EmailLogin = connect(null, mapDispatchToProps)(EmailLoginComponent);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  button: {
    marginTop: 28,
  },
});
