import Button from 'apsl-react-native-button';
import isEqual from 'lodash/isEqual';
import isNil from 'lodash/isNil';
import React, { Component } from 'react';
import { Alert, ScrollView, StyleSheet, Text, View } from 'react-native';
import * as Animatable from 'react-native-animatable';
import I18n from 'react-native-i18n';
import { responsiveHeight, responsiveWidth } from 'react-native-responsive-dimensions';
import { ProgressDialog } from 'react-native-simple-dialogs';
import { Fumi } from 'react-native-textinput-effects';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Color } from '../../config/Color';
import { FontWeight, Typography } from '../../config/typography';
import { store } from "../../redux/store";
import { IlinkEmitter } from '../../utils/events';
import { readUser } from '../../webservice/AuthApi';
import { joinGroupAction, joinGroupReset } from '../../webservice/NanoCreditApi';
let theme = require('../../utils/theme.json');
let route = require('../../route.json');


class AdhererGroupNanoCredit extends Component {

     static navigatorStyle = {
          navBarBackgroundColor: Color.primaryColor,
          statusBarColor: Color.primaryDarkColor,
          navBarTextColor: '#FFFFFF',
          navBarButtonColor: '#FFFFFF'

     };

     static navigationOptions = () => {
          return {
               drawerLabel: () => null,
               headerTitle: I18n.t('JOIN_GROUP'),
               headerTintColor: 'white',
               headerStyle: {
                    backgroundColor: Color.primaryColor,
                    marginTop: 0,
                    color: 'white'
               },
               headerTitleStyle: {
                    color: "white"
               },
               title: I18n.t('JOIN_GROUP')
          }
     };

     constructor(props) {
          super(props);
          this.state = {
               codeGroupe: null,
               codeSponsor: null,
               nomGroupe: null,
               codeSponsor: null,
               user: null,
               triggerSubmitClick: false,
               isSubmitClick: false,
               isDataSubmit: false,
               isModalConfirmVisible: false,
               wallet: store.getState().walletDetailReducer.result.response
          };

     }

     componentDidMount() {

          readUser().then((user) => {
               if (user) {
                    if (user !== undefined) {
                         this.setState({ user });
                    }
               }
          });

     }

     ckeckIfFieldIsOK(champ) {
          return (isNil(champ) || isEqual(champ.length, 0));
     }

     renderCreateGroupReponse = () => {

          const { result, error } = this.props;

          if (error !== null) {
               if (typeof error.data !== 'undefined') {
                    Alert.alert(
                         I18n.t("ERROR_JOIN_GROUP"),
                         error.data.error,
                         [
                              {
                                   text: I18n.t("OK"), onPress: () => {
                                        this.props.joinGroupReset();
                                   }
                              }
                         ],
                         { cancelable: false }
                    )
               }
          }

          if (result !== null) {
               if (result.response !== null) {
                    Alert.alert(
                         I18n.t("SUCCES_JOIN_GROUP"),
                         result.response,
                         [
                              {
                                   text: I18n.t("OK"), onPress: () => {
                                        this.props.joinGroupReset();
                                        IlinkEmitter.emit("treatNanoGroupDemand");
                                        this.props.navigation.pop();
                                   }
                              }

                         ],
                         { cancelable: false }
                    )
               }
          }
     }

     updateLangue() {
          this.props.navigation.setParams({ name: I18n.t('DEPOSIT_TO_CARD') })
          this.forceUpdate()
     }


     onSubmitSendWalletToCard = () => {
          const { codeGroupe, codeSponsor } = this.state;

          if (this.ckeckIfFieldIsOK(codeGroupe))
               this.nomGroupeAnim.shake(800);
          else if (this.ckeckIfFieldIsOK(codeSponsor))
               this.nomGroupeAnim.shake(800);
          else {

               this.props.joinGroupAction({
                    id_user: this.state.user.id,
                    code_groupe: this.state.codeGroupe,
                    code_sponsor: this.state.codeSponsor,
               });

          }
          this.setState({
               isDataSubmit: true
          });
     }


     renderLoader = () => {
          return (
               <ProgressDialog
                    visible={this.props.loading}
                    title={I18n.t('LOADING')}
                    message={I18n.t('LOADING_INFO')}
               />
          )
     }

     render() {
          return (
               <>
                    {(this.props.loading) && this.renderLoader()}
                    {this.state.isDataSubmit && this.renderCreateGroupReponse()}
                    <ScrollView style={styles.container}>

                         <Text style={styles.subbigtitle}>{I18n.t('GROUP_INFOS')}</Text>

                         <Animatable.View ref={(comp) => { this.nomGroupeAnim = comp }}>
                              <Fumi iconClass={FontAwesomeIcon} iconName={'code'}
                                   label={I18n.t('GROUP_CODE')}
                                   iconColor={'#f95a25'}
                                   iconSize={20}
                                   value={this.state.codeGroupe}
                                   onChangeText={(codeGroupe) => {

                                        this.setState({ codeGroupe })
                                   }}
                                   style={styles.input}
                              >
                              </Fumi>
                         </Animatable.View>

                         <Animatable.View ref={(comp) => { this.codeSponsorAnim = comp }}>
                              <Fumi iconClass={FontAwesomeIcon} iconName={'user-secret'}
                                   label={I18n.t('CODE_SPONSOR')}
                                   iconColor={'#f95a25'}
                                   iconSize={20}
                                   value={this.state.codeSponsor}
                                   onChangeText={(codeSponsor) => {

                                        this.setState({ codeSponsor })
                                   }}
                                   style={styles.input}
                              >
                              </Fumi>
                         </Animatable.View>

                         <Button style={styles.btnvalide}
                              textStyle={styles.textbtnvalide}
                              onPress={() => { this.onSubmitSendWalletToCard(); }}>
                              {I18n.t('SUBMIT_LABEL')}</Button>
                    </ScrollView>
               </>
          )
     }
}

const maptStateToProps = state => ({

     loading: state.joinGroupReducer.loading,
     result: state.joinGroupReducer.result,
     error: state.joinGroupReducer.error,
});

const mapDispatchToProps = dispatch => bindActionCreators({

     joinGroupAction,
     joinGroupReset,

}, dispatch);

export default connect(maptStateToProps, mapDispatchToProps)(AdhererGroupNanoCredit);

const styles = StyleSheet.create({
     container: {
          flex: 1,
          backgroundColor: Color.primaryDarkColor,
     },
     textbtnvalide: {
          color: 'white',
          fontWeight: 'bold'
     },
     bigtitle: {
          color: 'white',
          fontSize: 20,
          flex: 1,
          fontWeight: 'bold',
          textAlign: 'center',
          margin: 20,
     },
     blockView: {
          paddingVertical: 10,
          borderBottomWidth: 1
     },
     subbigtitle: {
          color: 'white',
          fontSize: 17,
          textAlign: 'center',
          margin: 5,
     },
     btnvalide: {
          marginTop: 20,
          marginLeft: 20,
          marginRight: 20,
          borderColor: 'transparent',
          backgroundColor: Color.accentLightColor,
          height: 52
     },
     btnSubmit: {
          marginTop: 20,
          borderColor: 'transparent',
          backgroundColor: Color.accentLightColor,
          height: 52,
          width: "30%",
          marginLeft: 20,
          marginRight: 20,
     },
     input: {
          height: 60,
          marginTop: responsiveHeight(2),
          marginLeft: responsiveWidth(5),
          marginRight: responsiveWidth(5),
          borderRadius: 5,
     }
});