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 {readUser} from '../../../webservice/AuthApi';
import {isNormalInteger} from '../../../utils/UtilsFunction';
import {askNanoCreditAction, getNanoCreditDemandDurationAction} from '../../../webservice/NanoCreditApi';
import {Dropdown} from 'react-native-material-dropdown-v2';
import {
    getIlinkBankAction,
    getIlinkBankReset,
    reattachAccountAction,
    reattachAccountReset
} from "../../../webservice/WalletApi";

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


class ReattachAccountUser extends Component {

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

    };

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

    constructor(props) {
        super(props);
        this.state = {
            codeGroupe: null,
            codeSponsor: null,
            nomGroupe: null,
            user: null,
            iban: null,
            bankToSend: null,
            ilinkBanks: [],
            bankSelect: null,
            triggerSubmitClick: false,
            hasLoadBank: false,
            modalVisible: false,
            isSubmitClick: false,
            isDataSubmit: false,
            isModalConfirmVisible: false,
            wallet: store.getState().walletDetailReducer.result.response
        };

        this.props.getIlinkBankReset();
        this.props.getIlinkBankAction(this.state.wallet.id_wallet_network);

    }

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

    renderIlinkBankList = () => {
        const {resultGetBank, errorGetBank} = this.props;
        if (resultGetBank !== null) {
            if (typeof resultGetBank.response !== 'undefined') {
                if (resultGetBank.response.length > 0) {
                    this.setState({
                        hasLoadBank: true,
                        ilinkBanks: resultGetBank.response,
                        bankSelect: resultGetBank.response[0].bank_name + " - " + resultGetBank.response[0].bank_address,
                        bankToSend: resultGetBank.response[0],
                        modalVisible: false
                    });
                } else if (resultGetBank.response.length === 0) {
                    this.setState({
                        hasLoadBank: true,
                        ilinkBanks: [],
                        bankSelect: '',
                        bankToSend: null,
                        modalVisible: false
                    });
                }
            }
        }

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

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

                    ],
                    {cancelable: false}
                )
            }
        }
    }


    renderReattachAccountResponse = () => {

        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.reattachAccountReset();
                            }
                        }
                    ],
                    {cancelable: false}
                )
            }
        }

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

                    ],
                    {cancelable: false}
                )
            }
        }
    }

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


    onSubmitSendWalletToCard = () => {
        const {iban, bankSelect} = this.state;

        if (this.ckeckIfFieldIsOK(bankSelect))
            this.listBankAnim.shake(800);
        else if (this.ckeckIfFieldIsOK(iban))
            this.ibanAnim.shake(800);
        else {
            console.warn("Code Iban", this.state.iban);
            console.warn("Bank", this.state.bankToSend);

                        this.props.reattachAccountAction({
                            iban: this.state.iban,
                            id_bank: this.state.bankToSend.id_bank,
                            id_wallet_network: this.state.wallet.id_wallet_network,
                            id_user: this.state.user.id
                        });

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


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

    render() {
        console.log(this.state);
        return (
            <>
                {(this.props.loading || this.props.loadingGetBank) && this.renderLoader()}
                {this.state.isDataSubmit && this.renderReattachAccountResponse()}
                {!this.state.hasLoadBank && this.renderIlinkBankList()}
                <ScrollView style={styles.container}>

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

                    <Animatable.View ref={(comp) => {
                        this.listBankAnim = comp
                    }}
                                     style={{
                                         width: responsiveWidth(90),
                                         height: 60,
                                         marginTop: 20,
                                         alignSelf: 'center',
                                         borderRadius: 10,
                                         paddingLeft: 20,
                                         paddingRight: 20,
                                         backgroundColor: 'white'
                                     }}>
                        <Dropdown
                            label={I18n.t('BANK_LIST')}
                            data={this.state.ilinkBanks}
                            useNativeDriver={true}
                            value={this.state.bankSelect !== null ? this.state.bankSelect : ''}
                            onChangeText={(value, index, data) => {
                                console.log(value);
                                this.setState({
                                    bankSelect: value.bank_name + " - " + value.bank_address,
                                    bankToSend: value
                                });
                            }}
                            valueExtractor={(value) => {
                                return value
                            }}
                            labelExtractor={(value) => {
                                return value.bank_name + " - " + value.bank_address
                            }}
                        />
                    </Animatable.View>

                    <Animatable.View ref={(comp) => {
                        this.ibanAnim = comp
                    }}>
                        <Fumi iconClass={FontAwesomeIcon} iconName={'id-card'}
                              label={I18n.t('CODE_IBAN')}
                              iconColor={'#f95a25'}
                              iconSize={20}
                              value={this.state.iban}
                              onChangeText={(iban) => {
                                  this.setState({iban})
                              }}
                              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 => ({
    loadingGetBank: state.getIlinkBankReducer.loading,
    resultGetBank: state.getIlinkBankReducer.result,
    errorGetBank: state.getIlinkBankReducer.error,

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

const mapDispatchToProps = dispatch => bindActionCreators({

    getIlinkBankAction,
    getIlinkBankReset,

    reattachAccountAction,
    reattachAccountReset,

    askNanoCreditAction,

    getNanoCreditDemandDurationAction,

}, dispatch);

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

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