/**
 * React Native Full App (https://store.enappd.com/product/react-native-full-app)
 *
 * Copyright © 2019-present Enappd. All rights reserved.
 *
 * This source code is licensed as per the terms found in the
 * LICENSE.md file in the root directory of this source tree.
 */
import React, { Component } from 'react';
import { Root } from 'native-base';
import VerificationView from './verficationView';
import { NavigationStackScreenProps } from 'react-navigation-stack';
import { connect } from 'react-redux';
import { AppReduxState } from '../../../redux/reducers';
import { bindActionCreators } from 'redux';
import { loginUser } from '../../../redux/actions/Authentication';
import { showToast } from '../../../utils';

interface Iprops extends NavigationStackScreenProps {
  verificationCode: string;
  actions: any;
  phoneNumber: string;
}

interface Istates {
  otpCode: string;
}

class VerificationContainer extends Component<Iprops, Istates> {
  static navigationOptions = {
    headerShown: false,
  };

  constructor(props: Iprops) {
    super(props);
    this.state = {
      otpCode: '',
    };
  }

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

  gotoHome = () => {
    if (this.state.otpCode === this.props.verificationCode) {
      const { navigation, actions, phoneNumber } = this.props;
      actions.loginUser(phoneNumber);
      navigation.navigate('App');
      //code to do
    } else {
      showToast('Invalid code. Please enter a valid code.', 'top');
    }
  };

  onTextChange = (otpCode: string) => this.setState({ otpCode });

  render() {
    return (
      <Root>
        <VerificationView
          otpCode={this.state.otpCode}
          onTextChange={this.onTextChange}
          goBack={this.goBack}
          gotoHome={this.gotoHome}
          verificationCode={this.props.verificationCode}
        />
      </Root>
    );
  }
}

const mapStateToProps = (state: AppReduxState) => {
  return {
    verificationCode: state.auth.verificationCode,
    phoneNumber: state.auth.phoneNumber,
  };
};
const matchDispatchToProps = (dispatch: any) => ({
  actions: bindActionCreators({ loginUser }, dispatch),
});

export default connect(
  mapStateToProps,
  matchDispatchToProps
)(VerificationContainer);
