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 Dialog from "react-native-dialog";
import { Dropdown } from 'react-native-material-dropdown-v2';
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 { store } from "../../../redux/store";
import { identityPieces, isIlinkWorldWallet, isNormalInteger, typeIdIDestinataire, thousandsSeparators } from '../../../utils/UtilsFunction';
import { readUser } from '../../../webservice/AuthApi';
import { checkIdTransactionAction, checkIdTransactionReset } from '../../../webservice/agent/RetraitCarteVersCashAgentApi';
import { envoieUserWalletToCardAction, envoieUserWalletToCardReset } from '../../../webservice/EnvoieUserApi';
import { Typography, FontWeight } from '../../../config/typography';
import thousands from 'thousands';
import { IlinkEmitter } from '../../../utils/events';
let theme = require('../../../utils/theme.json');
let route = require('../../../route.json');


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

     };

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

     constructor(props) {
          super(props);
          this.state = {
               identityPieces: identityPieces(),
               type_document_destinataire: (identityPieces()[0]).name,
               idTransaction: null,
               nom_destinataire: null,
               prenom_destinataire: null,
               numeroIdentite: null,
               montant: null,
               password: null,
               loading: false,
               codeRetrait: null,
               user: null,
               triggerSubmitClick: false,
               triggerNextClick: false,
               displayFirstStep: true,
               displaySecondStep: false,
               wallet: store.getState().walletDetailReducer.result.response
          };

          this.props.checkIdTransactionReset();
          this.props.envoieUserWalletToCardReset();
     }

     componentDidMount() {

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

     }

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

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

          else if (!isNormalInteger(montant))
               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
               };
     }

     onSubmitRetraitCash = () => {
          const { codeRetrait, montant, password } = this.state;

          if (this.ckeckIfFieldIsOK(montant))
               this.montantAnim.shake(800);
          else if (this.ckeckIfFieldIsOK(password))
               this.passwordAnim.shake(800);
          else {

               this.props.envoieUserWalletToCardAction({
                    type: 12,
                    id_wallet_agent: this.state.wallet.id,
                    id_transaction: this.state.idTransaction,
                    code_retrait: this.state.codeRetrait,
                    montant: this.state.montant,
                    password: this.state.password
               });
          }
          this.setState({
               triggerSubmitClick: true
          });

     }

     onSubmitNextStep = () => {

          const { idTransaction, codeRetrait } = this.state;
          this.props.checkIdTransactionReset();
          if (this.ckeckIfFieldIsOK(idTransaction))
               this.idTransactionAnim.shake(800);
          else if (this.ckeckIfFieldIsOK(codeRetrait))
               this.codeRetraitAnim.shake(800);
          else {
               this.props.checkIdTransactionAction({
                    id_transaction: idTransaction,
                    id_wallet_agent: this.state.wallet.id,
                    code_retrait: this.state.codeRetrait
               });
               this.setState({ triggerNextClick: true });
          }
     }

     renderRetraitEnCashAgentResponse = () => {
          const { resultEnvoieWalletToCard, errorEnvoieWalletToCard } = this.props;

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

          if (resultEnvoieWalletToCard !== null) {
               if (resultEnvoieWalletToCard.response !== null) {
                    Alert.alert(
                         I18n.t("WITHDRAWAL_SUCCESS"),
                         resultEnvoieWalletToCard.response,
                         [
                              {
                                   text: I18n.t("OK"), onPress: () => {
                                        this.props.envoieUserWalletToCardReset();
                                        IlinkEmitter.emit("refreshWallet");
                                        this.props.navigation.pop();
                                   }
                              }

                         ],
                         { cancelable: false }
                    )
               }
          }
     }

     renderTransactionIdVerification = () => {

          const { resultIdRetraitEnCash, errorIdRetraitEnCash } = this.props;

          console.log("PROPS", this.props);

          if (resultIdRetraitEnCash !== null) {
               console.log("resultIdVerification", resultIdRetraitEnCash);
               if (resultIdRetraitEnCash.status === 200) {
                    this.setState({
                         id_document_destinataire: resultIdRetraitEnCash.response.id_document_destinataire,
                         nom_destinataire: resultIdRetraitEnCash.response.nom_destinataire,
                         prenom_destinataire: resultIdRetraitEnCash.response.prenom_destinataire,
                         type_document_destinataire: resultIdRetraitEnCash.response.type_document_destinataire,
                         montant: resultIdRetraitEnCash.response.montant,
                         displayFirstStep: !this.state.displayFirstStep,
                         displaySecondStep: !this.state.displaySecondStep,
                    });
                    this.props.checkIdTransactionReset();
               }
          }

          if (errorIdRetraitEnCash !== null) {
               if (typeof errorIdRetraitEnCash.data !== 'undefined') {
                    Alert.alert(
                         I18n.t('ERROR_LABLE'),
                         errorIdRetraitEnCash.data.error,
                         [
                              {
                                   text: I18n.t("OK"), onPress: () => {
                                        this.props.checkIdTransactionReset();
                                        this.setState({ triggerNextClick: false })
                                   }
                              }

                         ],
                         { cancelable: false }
                    )
               } else {
                    Alert.alert(
                         I18n.t('ERROR_LABLE'),
                         JSON.stringify(errorIdRetraitEnCash),
                         [
                              {
                                   text: I18n.t("OK"), onPress: () => {
                                        this.props.checkIdTransactionReset();
                                   }
                              }

                         ],
                         { cancelable: false }
                    )
               }
          }
     }

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

     render() {
          console.log("STATE", this.state);
          return (
               <>
                    {(this.props.loadingIdRetraitEnCash || this.props.loadingEnvoieWalletToCard) && this.renderLoader()}
                    {this.state.triggerNextClick && this.renderTransactionIdVerification()}
                    {this.state.triggerSubmitClick && this.renderRetraitEnCashAgentResponse()}

                    <ScrollView style={styles.container}>

                         {this.state.displayFirstStep &&
                              <>

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

                                   <Animatable.View ref={(comp) => { this.idTransactionAnim = comp }}>
                                        <Fumi iconClass={FontAwesomeIcon} iconName={'barcode'}
                                             label={`${I18n.t('ID_TRANSACTION')}`}
                                             iconColor={'#f95a25'}
                                             iconSize={20}
                                             onChangeText={(idTransaction) => {
                                                  this.setState({ idTransaction })
                                             }}
                                             style={styles.input}
                                        >
                                        </Fumi>
                                   </Animatable.View>

                                   <Animatable.View ref={(comp) => { this.codeRetraitAnim = comp }}>
                                        <Fumi iconClass={FontAwesomeIcon} iconName={'lock'}
                                             value={this.state.codeRetrait}
                                             label={`${I18n.t('CODE_RETRAIT')}`}
                                             iconColor={'#f95a25'}
                                             iconSize={20}
                                             onChangeText={(codeRetrait) => {
                                                  this.setState({ codeRetrait })
                                             }}
                                             style={styles.input}
                                        >
                                        </Fumi>
                                   </Animatable.View>

                                   <Button style={styles.btnvalide}
                                        textStyle={styles.textbtnvalide}
                                        isLoading={this.state.isLoging}
                                        onPress={() => { this.onSubmitNextStep() }}>
                                        {I18n.t('NEXT')}</Button>

                              </>
                         }


                         {this.state.displaySecondStep &&
                              <>

                                   <Animatable.View ref={(comp) => { this.firstnameAnim = comp }}>
                                        <Fumi iconClass={FontAwesomeIcon} iconName={'user'}
                                             label={`${I18n.t('NAME')}`}
                                             iconColor={'#f95a25'}
                                             iconSize={20}
                                             editable={false}
                                             value={this.state.nom_destinataire}
                                             style={styles.input}
                                        >
                                        </Fumi>
                                   </Animatable.View>

                                   <Animatable.View ref={(comp) => { this.lastnameAnim = comp }}>
                                        <Fumi iconClass={FontAwesomeIcon} iconName={'user-circle-o'}
                                             label={`${I18n.t('FIRSTNAME')}`}
                                             iconColor={'#f95a25'}
                                             iconSize={20}
                                             editable={false}
                                             value={this.state.prenom_destinataire}
                                             style={styles.input}
                                        >
                                        </Fumi>
                                   </Animatable.View>

                                   <Animatable.View ref={(comp) => { this.identityPiecesAnim = comp }}
                                        style={{
                                             width: responsiveWidth(90),
                                             height: 60,
                                             marginTop: 20,
                                             alignSelf: 'center',
                                             borderRadius: 10,
                                             paddingLeft: 20,
                                             paddingRight: 20,
                                             backgroundColor: 'white'
                                        }}>
                                        <Dropdown
                                             label={I18n.t('PIECE_IDENTITE')}
                                             data={this.state.identityPieces}
                                             useNativeDriver={true}
                                             disabled={true}
                                             value={this.state.type_document_destinataire}
                                             valueExtractor={(value) => { return value.name }}
                                             labelExtractor={(value) => { return value.name }}
                                        />
                                   </Animatable.View>

                                   <Animatable.View ref={(comp) => { this.codeUtilisateurAnim = comp }}>
                                        <Fumi iconClass={FontAwesomeIcon} iconName={'address-card'}
                                             label={`${I18n.t('NUMERO_IDENTITE')}`}
                                             iconColor={'#f95a25'}
                                             iconSize={20}
                                             editable={false}
                                             value={this.state.id_document_destinataire}
                                             style={styles.input}
                                        >
                                        </Fumi>
                                   </Animatable.View>

                                   <Animatable.View ref={(comp) => { this.montantAnim = comp }}>
                                        <Fumi iconClass={FontAwesomeIcon} iconName={'money'}
                                             label={I18n.t('AMOUNT')}
                                             iconColor={'#f95a25'}
                                             iconSize={20}
                                             editable={false}
                                             value={`${this.state.montant}`}
                                             style={styles.input}
                                        />
                                        <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.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}
                                        isLoading={this.state.isLoging}
                                        onPress={() => { this.onSubmitRetraitCash() }}>
                                        {I18n.t('SUBMIT_LABEL')}</Button>

                              </>
                         }

                    </ScrollView>
               </>
          )
     }
}

const maptStateToProps = state => ({
     loadingIdRetraitEnCash: state.retraitCashAgentIdVerificationReducer.loading,
     resultIdRetraitEnCash: state.retraitCashAgentIdVerificationReducer.result,
     errorIdRetraitEnCash: state.retraitCashAgentIdVerificationReducer.error,


     loadingEnvoieWalletToCard: state.envoieUserWalletToCardReducer.loading,
     resultEnvoieWalletToCard: state.envoieUserWalletToCardReducer.result,
     errorEnvoieWalletToCard: state.envoieUserWalletToCardReducer.error,

});

const mapDispatchToProps = dispatch => bindActionCreators({
     checkIdTransactionAction,
     checkIdTransactionReset,

     envoieUserWalletToCardAction,
     envoieUserWalletToCardReset

}, dispatch);

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

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