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 { createGroupAction, createGroupReset } from '../../webservice/NanoCreditApi';
import { isNormalInteger } from '../../utils/UtilsFunction';
let theme = require('../../utils/theme.json');
let route = require('../../route.json');


class CreateGroupNanoCredit extends Component {


     constructor(props) {
          super(props);
          this.state = {
               montant: null,
               password: null,
               nomGroupe: null,
               limitCredit: null,
               codeSponsor1: null,
               codeSponsor2: null,
               codeSponsor3: null,
               codeGroup: null,
               loading: false,
               user: null,
               triggerSubmitClick: false,
               isSubmitClick: false,
               isDataSubmit: false,
               isModalConfirmVisible: false,
               isGroupToModify: false,
               wallet: store.getState().walletDetailReducer.result.response
          };

     }

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

     };

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

     componentDidMount() {

          readUser().then((user) => {
               if (user) {
                    if (user !== undefined) {
                         const groupToModify = this.props.navigation.getParam('group', null);
                         if (!isNil(groupToModify)) {
                              this.setState({
                                   limitCredit: groupToModify.limite_credit,
                                   nomGroupe: groupToModify.nom,
                                   codeSponsor1: groupToModify.codeSponsor1,
                                   codeSponsor2: groupToModify.codeSponsor2,
                                   codeSponsor3: groupToModify.codeSponsor3,
                                   codeGroup: groupToModify.code_groupe,
                                   isGroupToModify: true
                              });
                         }
                         this.setState({ user });
                    }
               }
          });

     }

     isMontantValid = () => {
          const { limitCredit } = this.state;
          if ((parseInt(isEqual(limitCredit, 0)) || limitCredit < 0))
               return {
                    errorMessage: I18n.t('ENTER_AMOUNT_SUPERIOR_ZEROR'),
                    isValid: false
               };

          else if (!isNormalInteger(limitCredit))
               return {
                    errorMessage: I18n.t('ENTER_VALID_AMOUNT'),
                    isValid: false
               };

          /*           else if (montant > parseInt(this.state.comptePrincipal))
                         return {
                              errorMessage: I18n.t('AMOUNT_SUPERIOR_TO_PRINCIPAL_ACCOUNT'),
                              isValid: false
                         }; */

          else
               return {
                    errorMessage: '',
                    isValid: true
               };
     }

     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_CREATION_GROUP"),
                         error.data.error,
                         [
                              {
                                   text: I18n.t("OK"), onPress: () => {
                                        this.props.createGroupReset();
                                   }
                              }
                         ],
                         { cancelable: false }
                    )
               }
          }

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

                         ],
                         { cancelable: false }
                    )
               }
          }
     }

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

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

     onSubmitSendWalletToCard = () => {
          const { codeSponsor1, codeSponsor2, nomGroupe, codeSponsor3, limitCredit, password } = this.state;

          if (this.ckeckIfFieldIsOK(nomGroupe))
               this.nomGroupeAnim.shake(800);
          else if (this.ckeckIfFieldIsOK(limitCredit) || !this.isMontantValid().isValid) {
               this.limitCreditAnim.shake(800);
          }
          else if (this.ckeckIfFieldIsOK(codeSponsor1))
               this.codeSponsor1Anim.shake(800);
          else if (this.ckeckIfFieldIsOK(codeSponsor2))
               this.codeSponsor2Anim.shake(800);
          else if (this.ckeckIfFieldIsOK(codeSponsor3))
               this.codeSponsor3Anim.shake(800);
          else if (this.ckeckIfFieldIsOK(password))
               this.passwordAnim.shake(800);
          else {

               if (this.state.isGroupToModify) {

                    this.props.createGroupAction({
                         id_user: this.state.user.id,
                         nom: this.state.nomGroupe,
                         code_group: this.state.codeGroup,
                         code_sponsor1: this.state.codeSponsor1,
                         code_sponsor2: this.state.codeSponsor2,
                         code_sponsor3: this.state.codeSponsor3,
                         password: this.state.password,
                         limite_credit: this.state.limitCredit,
                         code_groupe: this.state.codeGroup
                    }, 1);
               } else {

                    this.props.createGroupAction({
                         id_user: this.state.user.id,
                         nom: this.state.nomGroupe,
                         code_sponsor1: this.state.codeSponsor1,
                         code_sponsor2: this.state.codeSponsor2,
                         code_sponsor3: this.state.codeSponsor3,
                         password: this.state.password,
                         limite_credit: this.state.limitCredit
                    }, 0);
               }
          }
          this.setState({
               isDataSubmit: true
          });
     }


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

     render() {
          return (
               <>
                    {(this.props.loading || this.props.loadingGetCommission) && 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={'id-card'}
                                   label={I18n.t('NOM_GROUP')}
                                   iconColor={'#f95a25'}
                                   iconSize={20}
                                   value={this.state.nomGroupe}
                                   onChangeText={(nomGroupe) => {

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

                         <Animatable.View ref={(comp) => { this.limitCreditAnim = comp }}>
                              <Fumi iconClass={FontAwesomeIcon} iconName={'money'}
                                   label={I18n.t('LIMIT_OF_CREDIT')}
                                   iconColor={'#f95a25'}
                                   keyboardType='numeric'
                                   iconSize={20}
                                   value={this.state.limitCredit}
                                   onChangeText={(limitCredit) => {
                                        this.setState({ limitCredit })
                                   }}
                                   style={styles.input}
                              >
                              </Fumi>
                              <View style={{
                                   position: 'absolute',
                                   left: responsiveWidth(82),
                                   top: 35,
                                   flexDirection: 'row'
                              }}>
                                   <View
                                        style={{
                                             width: 1,
                                             borderLeftColor: '#f0f0f0',
                                             height: 40,
                                             left: -8,
                                             top: -10,
                                             borderLeftWidth: 1,

                                        }}
                                   />
                                   <Text style={[Typography.body1, FontWeight.bold]}>{this.state.wallet.currency_code}</Text>
                              </View>
                         </Animatable.View>

                         <Animatable.View ref={(comp) => { this.codeSponsor1Anim = comp }}>
                              <Fumi iconClass={FontAwesomeIcon} iconName={'user-circle-o'}
                                   label={I18n.t('CODE_USER_ILINK_SPONSOR_1')}
                                   iconColor={'#f95a25'}
                                   iconSize={20}
                                   value={this.state.codeSponsor1}
                                   onChangeText={(codeSponsor1) => {

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

                         <Animatable.View ref={(comp) => { this.codeSponsor2Anim = comp }}>
                              <Fumi iconClass={FontAwesomeIcon} iconName={'user-circle-o'}
                                   label={I18n.t('CODE_USER_ILINK_SPONSOR_2')}
                                   iconColor={'#f95a25'}
                                   iconSize={20}
                                   value={this.state.codeSponsor2}
                                   onChangeText={(codeSponsor2) => {

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

                         <Animatable.View ref={(comp) => { this.codeSponsor3Anim = comp }}>
                              <Fumi iconClass={FontAwesomeIcon} iconName={'user-circle-o'}
                                   label={I18n.t('CODE_USER_ILINK_SPONSOR_3')}
                                   iconColor={'#f95a25'}
                                   iconSize={20}
                                   value={this.state.codeSponsor3}
                                   onChangeText={(codeSponsor3) => {

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

                         <Animatable.View ref={(comp) => { this.passwordAnim = comp }}>
                              <Fumi iconClass={FontAwesomeIcon} iconName={'lock'}
                                   label={I18n.t('PASSWORD')}
                                   iconColor={'#f95a25'}
                                   iconSize={20}
                                   secureTextEntry={true}
                                   value={this.state.password}
                                   onChangeText={(password) => {
                                        this.setState({ password })
                                   }}
                                   style={styles.input}
                              >
                              </Fumi>
                         </Animatable.View>

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

const maptStateToProps = state => ({

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

const mapDispatchToProps = dispatch => bindActionCreators({

     createGroupAction,
     createGroupReset,

}, dispatch);

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

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,
     }
});