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 CustomButton from '../../../components/CustomButton';
import {bindActionCreators} from 'redux';
import {Color} from '../../../config/Color';
import {store} from "../../../redux/store";
import {identityPieces, isIlinkWorldWallet, isNormalInteger, typeIdIDestinataire} from '../../../utils/UtilsFunction';
import {readUser} from '../../../webservice/AuthApi';
import { CreditCardInput } from "react-native-credit-card-input";


import {
    getActiveCountryAction,
    getActiveCountryByDialCodeAction,
    getActiveCountryByDialCodeReset,
    getActiveCountryReset,
    getPayCountryNetworkAction,
    getPayCountryNetworkReset
} from '../../../webservice/CountryApi';
import {
    envoieUserWalletToWalletAction,
    envoieUserWalletToWalletReset,
    getCommissionUserWalletToWalletAction,
    getCommissionUserWalletToWalletReset,
    envoieUserWalletToCardReset,
    envoieUserWalletToCardAction
} from '../../../webservice/EnvoieUserApi';
import {FontWeight, Typography} from '../../../config/typography';
import thousands from 'thousands';
import {IlinkEmitter} from '../../../utils/events';
import { linkCardReset, linkCardAction } from '../../../webservice/WalletApi';

let theme = require('../../../utils/theme.json');
let route = require('../../../route.json');

class CarteLier extends Component {
     static navigatorStyle = {
          navBarBackgroundColor: Color.accentLightColor,
          statusBarColor: Color.accentColor,
          navBarTextColor: '#FFFFFF',
          navBarButtonColor: '#FFFFFF',
     };

     static navigationOptions = () => {
          return {
               drawerLabel: () => null,
               headerTitle: I18n.t('REATTACH__MY_CARD'),
               headerTintColor: 'white',
               headerStyle: {
                   backgroundColor: Color.primaryColor,
                   marginTop: 0,
                   color: 'white'
               },
               headerTitleStyle: {
                    color: "white"
                },
                title: I18n.t('REATTACH__MY_CARD')
            }
          //      header: null,
          //      headerMode: 'none',
          //      headerTitle: null,
          //      activeColor: '#f0edf6',
          //      inactiveColor: '#3e2465',
          // };
     }

    constructor(props) {
        super(props);
        this.state = {
           
            paysDestination: [],
            paysDestinationSelect: null,
           
          
            loading: false,
           
            numCarte: 0,
            cvv: 0,
            codeCVV: null,
            expiration_date: '',
            creditCardInput: {},
            user: null,
            nomsDestinataire: null,
            prenomsDestinataire: null,
            modalVisible: false,
            hasLoadActiveCountryList: true,
            hasLoadActivePayCountryNetworkList: true,
            triggerSubmitClick: false,
            isDataSubmit: false,
            isModalConfirmVisible: false,
            wallet: store.getState().walletDetailReducer.result.response,

            numCarte: 0,
            cvv: 0,
            expiration_date: '',
            displayCardError: false,
            isSubmitClick: false,
            user: null,
            countryCustomer: [],
            paysDestinationSelect: null,
            triggerNextClick: false,
            modalVisible: false,
        };
        this.props.linkCardReset();
        this.props.envoieUserWalletToCardReset();
        this.props.getActiveCountryReset();
        this.props.getActiveCountryByDialCodeReset();
        this.props.getPayCountryNetworkReset();
        this.props.envoieUserWalletToWalletReset();
        this.props.getCommissionUserWalletToWalletReset();

        this.props.getActiveCountryAction();
        console.log("ENVOIE WALLET PROPS", this.props);
    }

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

    }

    componentWillReceiveProps(nextProps) {

        if (nextProps.resultEnvoieWalletToWalletGetCommission != null) {

            if (typeof nextProps.resultEnvoieWalletToWalletGetCommission.response !== 'undefined') {

                if (!nextProps.loadingEnvoieWalletToWalletGetCommission)
                    this.setState({
                        isModalConfirmVisible: true
                    });
            }
        }
    }

   

    renderDialogResponse = () => {
     const { result, error } = this.props;

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

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

                    ],
                    { cancelable: false }
               )
          }
     }
}

renderGetActionCountryList = () => {

     const {resultActiveCountryList, errorActiveCountryList} = this.props;
     if (resultActiveCountryList !== null) {
         if (typeof resultActiveCountryList.response !== 'undefined') {

             this.setState({
                 hasLoadActiveCountryList: false,
                 paysDestination: resultActiveCountryList.response,
                 paysDestinationSelect: resultActiveCountryList.response[0].name,
             });
             if (this.state.hasLoadActivePayCountryNetworkList)
                 this.props.getPayCountryNetworkAction({
                     id_wallet_user: this.state.wallet.id,
                     id_country: resultActiveCountryList.response[0].id
                 });
         }
     }

     if (errorActiveCountryList !== null) {
         if (typeof errorActiveCountryList.data !== 'undefined') {
             Alert.alert(
                 I18n.t('ERROR_LABEL'),
                 errorActiveCountryList.data.error,
                 [
                     {
                         text: I18n.t("OK"), onPress: () => {
                             this.props.getActiveCountryReset();
                         }
                     }

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

                 ],
                 {cancelable: false}
             )
         }
     }
 }

onCreditCardChange = (form) => {
     this.setState({
          creditCardInput: form
     });
    //  if (values.number && values.number.length > 16){
    //     return;
    //  }
}
    

    isCreditCardValid = () => {
        const { creditCardInput } = this.state;
        const errorMessage = [];
        

        if (typeof creditCardInput.status !== 'undefined') {
           
             if (creditCardInput.status.cvc === 'incomplete')
                  errorMessage.push(I18n.t('CVC_CARD_ERROR') || secureTextEntry=='true');
             if (creditCardInput.status.expiry === 'incomplete')
                  errorMessage.push(I18n.t('EXPIRY_CARD_ERROR'));
             if (creditCardInput.status.number === 'incomplete')
                  errorMessage.push(I18n.t('CARD_NUMBER_ERROR'));
        }
        else
             errorMessage.push(I18n.t('THIS_FIELD_IS_REQUIRED'))

        return errorMessage;
   }

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


    onSubmit  = () => {
     const { creditCardInput, paysDestinationSelect, } = this.state;
      if (!creditCardInput.valid) {
          this.setState({
               displayCardError: true,
          });
     }
     else if (this.ckeckIfFieldIsOK(paysDestinationSelect))
     this.paysDestinationAnim.shake(800);

     else if (creditCardInput.valid) {

          this.setState({
               numCarte: parseInt((creditCardInput.values.number).replace(/\s/g, '')),
               expiration_date: creditCardInput.values.expiry,
          }, () => {
               this.props.linkCardAction({
                    numero_carte: this.state.numCarte,
                    expiration_date: this.state.expiration_date,
                    //customer_card: (this.state.countryCustomer.filter(element => element.name === this.state.paysDestinationSelect))[0].card_country_id,
                    card_country_id: (this.state.paysDestination.filter(element => element.name === this.state.paysDestinationSelect))[0].id,
               }, this.state.user.id);
          });
     }
   
     this.setState({ isSubmitClick: true });
    }

    renderLoader = () => {
        return (
            <ProgressDialog
                visible={this.state.modalVisible || this.props.loadingEnvoieWalletToWalletGetCommission || this.props.loadingEnvoieWalletToWallet || this.props.loadingCountryByDialCode || this.props.loadingActiveCountryList || this.props.loadingCountryByDialCode}
                title={I18n.t('LOADING')}
                message={I18n.t('LOADING_INFO')}
            />
        )
    }

    render() {
        console.log("STATE", this.state);
        const {resultEnvoieWalletToWalletGetCommission} = this.props;
        return (
            <>
                {(this.state.modalVisible || this.props.loadingEnvoieWalletToWalletGetCommission || this.props.loadingEnvoieWalletToWallet || this.props.loadingCountryByDialCode || this.props.loadingActiveCountryList || this.props.loadingCountryByDialCode) && this.renderLoader()}
                {this.state.isSubmitClick && this.renderDialogResponse()}
                {this.state.hasLoadActiveCountryList && this.renderGetActionCountryList()}
                {
                    (resultEnvoieWalletToWalletGetCommission !== null) &&
                    (typeof resultEnvoieWalletToWalletGetCommission.response !== 'undefined') &&
                    this.modalConfirmTransaction(resultEnvoieWalletToWalletGetCommission)
                }
                <ScrollView style={{ padding: 20 }}>

<View style={{ marginTop: 10 }}>
     <CreditCardInput
          validColor={this.state.creditCardInput.valid ? 'green' : ''}
          invalidColor={!this.state.creditCardInput.valid ? 'red' : ''}
          onChange={this.onCreditCardChange}
          requiresCVC={false}
          labels={{
               number: I18n.t('CARD_NUMBER_LABEL'),
               expiry: I18n.t('CARD_EXPIRY_LABEL')
          }} />
     {
          (this.state.displayCardError) &&
          this.isCreditCardValid().map((item) => (
               <Text style={{ color: 'red', marginLeft: 15 }}>{item}</Text>
          ))
     }
</View>
                    <Animatable.View ref={(comp) => {
                        this.paysDestinationAnim = comp
                    }}
                                     style={{
                                         width: responsiveWidth(90),
                                         height: 60,
                                         marginTop: 20,
                                         alignSelf: 'center',
                                         borderRadius: 10,
                                         paddingLeft: 20,
                                         paddingRight: 20,
                                         backgroundColor: 'white'
                                     }}>
                        <Dropdown
                            label={I18n.t('CARD_COUNTRY')}
                            data={this.state.paysDestination}
                            useNativeDriver={true}
                            value={this.state.paysDestinationSelect === null ? '' : this.state.paysDestinationSelect}
                            onChangeText={(value, index, data) => {
                                this.props.getPayCountryNetworkReset();

                                let countrySelect = data.filter(element => element.name === value);
                                this.setState({
                                    paysDestinationSelect: value,
                                    hasLoadActivePayCountryNetworkList: true
                                }, () => {
                                    this.props.getPayCountryNetworkAction({
                                        id_wallet_user: this.state.wallet.id,
                                        card_country_id: countrySelect[0].card_country_id
                                    });
                                });
                                this.props.getCommissionUserWalletToWalletReset();
                            }}
                            valueExtractor={(value) => {
                                return value.name
                            }}
                            labelExtractor={(value) => {
                                return value.name
                            }}
                        />
                    </Animatable.View>

                    <View style={{ marginTop: 20, marginLeft: 10, marginRight: 10 }}>
                                        <CustomButton loading={false} outline onPress={() => this.onSubmit()}>
                                             {I18n.t('VALIDATE')}
                                        </CustomButton>
                                   </View>
                </ScrollView>
            </>
        )
    }
}

const maptStateToProps = state => ({
     loading: state.linkCardReduder.loading,
     result: state.linkCardReduder.result,
     error: state.linkCardReduder.error,

    loadingCountryByDialCode: state.countryByDialCode.loading,
    resultCountryByDialCode: state.countryByDialCode.result,
    errorCountryByDialCode: state.countryByDialCode.error,

    loadingActiveCountryList: state.activeCountryListReducer.loading,
    resultActiveCountryList: state.activeCountryListReducer.result,
    errorActiveCountryList: state.activeCountryListReducer.error,

    loadingPayCountryNetwork: state.payCountryNetworkReducer.loading,
    resultPayCountryNetwork: state.payCountryNetworkReducer.result,
    errorPayCountryNetwork: state.payCountryNetworkReducer.error,

    loadingEnvoieWalletToWallet: state.envoieUserWalletToWalletReducer.loading,
    resultEnvoieWalletToWallet: state.envoieUserWalletToWalletReducer.result,
    errorEnvoieWalletToWallet: state.envoieUserWalletToWalletReducer.error,

    loadingEnvoieWalletToWalletGetCommission: state.envoieUserWalletToWalletGetCommissionReducer.loading,
    resultEnvoieWalletToWalletGetCommission: state.envoieUserWalletToWalletGetCommissionReducer.result,
    errorEnvoieWalletToWalletGetCommission: state.envoieUserWalletToWalletGetCommissionReducer.error,
});

const mapDispatchToProps = dispatch => bindActionCreators({

     linkCardAction,
     linkCardReset, 

    getActiveCountryByDialCodeAction,
    getActiveCountryByDialCodeReset,

    getPayCountryNetworkAction,
    getPayCountryNetworkReset,

    getActiveCountryAction,
    getActiveCountryReset,

    envoieUserWalletToWalletAction,
    envoieUserWalletToWalletReset,

    getCommissionUserWalletToWalletAction,
    getCommissionUserWalletToWalletReset,

    envoieUserWalletToCardReset,
    envoieUserWalletToCardAction,

}, dispatch);

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

const styles = StyleSheet.create({
     container: {
          flex: 1,
          backgroundColor: Color.containerBackgroundColor
     },
     checkDefault: {
          flexDirection: "row",
          justifyContent: "space-between",
          alignItems: "center",
          borderBottomWidth: 1,
          paddingVertical: 15,
          marginTop: 10
     },
     contentButtonBottom: {
          borderTopWidth: 1,
          paddingVertical: 10,
          paddingHorizontal: 20,
          flexDirection: "row",
          justifyContent: "space-between",
          alignItems: "center"
     },
     blockView: {
          paddingVertical: 10,
          borderBottomWidth: 1
     },
     lottie: {
          width: 248,
          height: 248
     },
});