import React from 'react';
import { View, Text, BackHandler, TextInput } from 'react-native';
import styles from './Styles/RegisterStyle';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { registerRequest } from './../../../actions/UserAction';
import {
  Container,
  Content,
  Button,
  HeaderBig,
  TouchableOpacity,
  Toast,
  Loader
} from './../../../components';
import i18n from './../../../i18n';
import { Colors, Images } from './../../../theme';
import { validateEmail } from './../../../libs/Utils';

export interface Props {
  navigation: any;
  register: any;
  loading: any;
}
interface State {
  firstName?: any;
  lastName: any;
  email: any;
  password: any;
  confirmPassword: any;
}
class RegisterScreen extends React.Component<Props, State> {
  registerRefs: any = {};

  constructor(props: Props) {
    super(props);
    this.state = {
      // firstName: 'Test1',
      // lastName: 'Test2',
      // email: 'meetp1@zlucksolutions.com',
      // password: '12345678',
      // confirmPassword: '12345678',
      firstName: '',
      lastName: '',
      email: '',
      password: '',
      confirmPassword: ''
    };
  }

  componentDidMount = () => {
    BackHandler.addEventListener('hardwareBackPress', this.backHandler);
  };

  componentWillUnmount = () => {
    BackHandler.removeEventListener('hardwareBackPress', this.backHandler);
  };

  backHandler = () => {
    const { navigation } = this.props;
    return navigation.goBack();
  };

  signUpPress = () => {
    const {
      firstName,
      lastName,
      email,
      password,
      confirmPassword
    } = this.state;
    const { register } = this.props;

    if (firstName.trim().length === 0) {
      Toast.errorBottom('Please enter first name');
      return;
    }
    if (lastName.trim().length === 0) {
      Toast.errorBottom('Please enter last name');
      return;
    }
    let emailRes = validateEmail(this.state.email);
    if (!emailRes.success) {
      Toast.errorBottom(emailRes.message);
      return false;
    }
    if (password.trim().length === 0) {
      Toast.errorBottom('Please enter password');
      return;
    }
    if (password.trim().length <= 6) {
      Toast.errorBottom('Password should be at least 6 characters');
      return;
    }
    if (confirmPassword.trim().length === 0) {
      Toast.errorBottom('Please enter confirm password');
      return;
    }
    if (password !== confirmPassword) {
      Toast.errorBottom('Password and confirm password does not match');
      return;
    }

    let params = {
      first_name: firstName,
      last_name: lastName,
      email: email,
      password: password,
      phone: '',
      image: null,
      address1: '',
      address2: '',
      city: '',
      state: '',
      zip: '',
      country_id: 0
    };

    register(params);
  };

  moveFocus = (key: any) => {
    let toFocus = null;
    switch (key) {
      case 'firstName':
        toFocus = this.registerRefs.lastName.focus();
        break;
      case 'lastName':
        toFocus = this.registerRefs.email.focus();
        break;
      case 'email':
        toFocus = this.registerRefs.password.focus();
        break;
      case 'password':
        toFocus = this.registerRefs.confirmPassword.focus();
        break;
      default:
        toFocus = null;
    }
    return toFocus;
  };

  renderInput = (key: any, value: any) => {
    return (
      <View style={styles.txtInputView}>
        <Text style={styles.labelTxt}>{i18n.t(`register.${key}`)}</Text>
        <TextInput
          ref={(node: any) => {
            this.registerRefs[key] = node;
          }}
          key={key}
          style={styles.txtInput}
          placeholder={'Enter ' + i18n.t(`register.${key}`)}
          returnKeyType="next"
          keyboardType={key === 'email' ? 'email-address' : 'default'}
          autoCapitalize={
            key === 'password' || key === 'confirmPassword' || key === 'email'
              ? 'none'
              : 'sentences'
          }
          secureTextEntry={key === 'password' || key === 'confirmPassword'}
          placeholderTextColor={Colors.borderGrey}
          value={value}
          onChangeText={val => {
            const obj: any = {};
            obj[key] = val;
            this.setState(obj);
          }}
          onSubmitEditing={() => {
            this.moveFocus(key);
          }}
        />
      </View>
    );
  };

  render() {
    const {
      firstName,
      lastName,
      email,
      password,
      confirmPassword
    } = this.state;
    const { navigation, loading } = this.props;
    return (
      <>
        <Container transparentStatusBar safeAreaView={false}>
          <Content hasBigHeader>
            <HeaderBig
              sideRightImageSource={Images.boy}
              sideRightImageStyle={styles.boyImg}
            />
           <View style={styles.bottom}>
            {this.renderInput('firstName', firstName)}
            {this.renderInput('lastName', lastName)}
            {this.renderInput('email', email)}
            {this.renderInput('password', password)}
            {this.renderInput('confirmPassword', confirmPassword)}

            <Button
              title={'REGISTER'}
              style={styles.marginTop20}
              long
              onPress={() => this.signUpPress()}
            />
</View>
            <View style={styles.bottomView}>
              <Text style={styles.bottomTipTxt}>Already have an account?</Text>
              <TouchableOpacity onPress={() => navigation.navigate('Login')}>
                <Text style={styles.loginTipTxt}>Login</Text>
              </TouchableOpacity>
            </View>
          </Content>
        </Container>
        <Loader show={loading} />
      </>
    );
  }
}

function mapStateToProps({ user }: any) {
  return {
    loading: user.loading
  };
}

function mapDispatchToProps(dispatch: any) {
  return bindActionCreators(
    {
      register: registerRequest
    },
    dispatch
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(RegisterScreen);
