import React, {Component} from 'react';
import {Alert, StatusBar, StyleSheet, Text, View} from 'react-native';
import I18n from 'react-native-i18n';
import {Appbar, Provider} from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {Color} from '../../config/Color';
import {IlinkEmitter} from "../../utils/events";
import OutlineTextInput from '../../components/OutlineTextInput';
import CustomButton from '../../components/CustomButton';
import {ScrollView} from 'react-native-gesture-handler';
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import {payBillAction, payBillReset} from "../../webservice/WalletApi";
import {store} from "../../redux/store";
import isEqual from 'lodash/isEqual';

const route = require('../../route.json');
let slugify = require('slugify');

class PaiementFacture extends Component {

    constructor(props) {
        super(props);
        IlinkEmitter.on("langueChange", this.updateLangue.bind(this));
        this.state = {
            title: this.props.navigation.state.params.title,
            type: this.props.navigation.state.params.type,
            id_operator: this.props.navigation.state.params.operator_id,
            typeOperator: this.props.navigation.state.params.typeOperator,
            billNumber: '',
            subscriberID: null,
            isSubmitClick: false,
            montant: '',
            password: '',
            wallet: store.getState().walletDetailReducer.result.response
        };
        this.props.payBillReset();
        console.log("Paiement facture props", this.props);
    }

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

    static navigationOptions = ({navigation}) => ({
        header: null,
        headerMode: 'none',
        headerTitle: null,
        activeColor: '#f0edf6',
        inactiveColor: '#3e2465',
        barStyle: {backgroundColor: '#694fad'},
        drawerLabel: I18n.t('CREDIT_MANAGE'),
        drawerIcon: ({tintColor}) => (
            <Icon
                name={'credit-card'}
                size={24}
            />)
    });

    isNormalInteger = (str) => {
        if (/[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/.test(str))
            return false;
        else
            return true;
    }

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

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

    renderErrorNumberBill = () => {
        const {type} = this.state;

        switch (type) {
            case 'PAIEMENT_ECOLE':
                return I18n.t('ENTER_VALID_IDENTIFIANT_ETUDIANT');
            case 'PAIEMENT_EAU':
                return I18n.t('ENTER_VALID_NUMERO_ABONNE');
            case 'PAIEMENT_EAU_ELECTRICITE':
                return I18n.t('ENTER_VALID_NUMERO_ABONNE');
            case 'PAIEMENT_CREDIT_TELEPHONE':
                return I18n.t('ENTER_VALID_PHONE_NUMBER');
            case 'PAIEMENT_ABONNEMENT_TV':
                return I18n.t('ENTER_VALID_NUMERO_ABONNE');
            default:
                break;
        }
    };

    isBillnumberValid = () => {
        const {billNumber} = this.state;
        if ((parseInt(isEqual(billNumber, 0)) || billNumber < 0))
            return {
                errorMessage: this.renderErrorNumberBill(),
                isValid: false
            };
        else if (billNumber.length > 11) {
            return {
                errorMessage: this.renderErrorNumberBill(),
                isValid: false
            };
        } else
            return {
                errorMessage: '',
                isValid: false
            };
    };

    renderLabel = () => {
        const {type} = this.state;

        switch (type) {
            case 'PAIEMENT_ECOLE':
                return I18n.t('IDENTIFIANT_ETUDIANT');
            case 'PAIEMENT_EAU':
                return I18n.t('NUMERO_ABONNE');
            case 'PAIEMENT_EAU_ELECTRICITE':
                return I18n.t('NUMERO_ABONNE');
            case 'PAIEMENT_CREDIT_TELEPHONE':
                return I18n.t('PHONE_NUMBER');
            case 'PAIEMENT_ABONNEMENT_TV':
                return I18n.t('NUMERO_ABONNE');
            default:
                break;
        }
    };

    renderPayBill = () => {

        const {result, error} = this.props;

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

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

                    ],
                    {cancelable: false}
                )
            }
        }
    };

    onPayBill = () => {
        console.log("this.isBillnumberValid().isValid", this.isBillnumberValid().isValid);
        console.log("this.isMontantValid().isValid", this.isMontantValid().isValid);
        console.log("this.state.montant.length > 0", this.state.montant.length > 0);
        console.log("this.state.password.length > 0", this.state.password.length > 0);
        this.setState({isSubmitClick: true});
        if (/*this.isBillnumberValid().isValid && this.isMontantValid().isValid &&*/ this.state.montant.length > 0 && this.state.password.length > 0) {

            this.props.payBillAction({
                type: 19,
                id_wallet_user: this.state.wallet.id,
                id_wallet_network: this.state.wallet.id_wallet_network,
                no_facture: this.state.billNumber,
                type_operator: this.state.typeOperator,
                id_operator: this.state.id_operator,
                montant: this.state.montant,
                password: this.state.password
            });
        }
    }

    render() {
        console.log("this.isBillnumberValid().isValid", this.isBillnumberValid().isValid);
        console.log("this.isMontantValid().isValid", this.isMontantValid().isValid);
        console.log("this.state.montant.length > 0", this.state.montant.length > 0);
        console.log("this.state.password.length > 0", this.state.password.length > 0);
        console.log("-------------------------------");
        return (
            <Provider>
                <View style={{flex: 1}}>
                    {this.state.isSubmitClick && this.renderPayBill()}
                    <StatusBar
                        backgroundColor={Color.primaryDarkColor}
                        barStyle="light-content"
                        translucent={false}
                    />

                    <Appbar.Header dark={true} style={{backgroundColor: Color.primaryColor}}>
                        <Appbar.BackAction
                            onPress={() => {
                                this.props.navigation.pop()
                            }}
                        />
                        <Appbar.Content
                            title={this.state.title}
                        />
                    </Appbar.Header>

                    <View style={styles.container}>
                        <ScrollView style={{padding: 20}}>

                            <View style={{marginTop: 10, marginRight: 20, marginLeft: 20}}>
                                <OutlineTextInput
                                    borderBottomColor={!this.isBillnumberValid().isValid ? 'black' : 'red'}
                                    value={this.state.billNumber}
                                    label={this.renderLabel()}
                                    style={{marginTop: 10}}
                                    placeholder={this.renderLabel()}
                                    onChangeText={(billNumber) => {
                                        this.setState({billNumber});
                                        this.isBillnumberValid();
                                    }}
                                />
                                {
                                    (!this.isBillnumberValid().isValid) &&
                                    <Text
                                        style={{
                                            color: 'red',
                                            marginTop: 2
                                        }}>{this.isBillnumberValid().errorMessage}</Text>
                                }
                                {
                                    (this.state.isSubmitClick && this.state.billNumber.length === 0) &&
                                    <Text
                                        style={{color: 'red', marginTop: 2}}>{this.renderErrorNumberBill()}</Text>
                                }
                            </View>

                            <View style={{marginTop: 10, marginRight: 20, marginLeft: 20, marginBottom: 10}}>
                                <OutlineTextInput
                                    borderBottomColor={!this.isMontantValid().isValid ? 'black' : 'red'}
                                    value={this.state.montant}
                                    keyboardType="numeric"
                                    label={I18n.t('AMOUNT_LABEL')}
                                    style={{marginTop: 10}}
                                    placeholder={I18n.t('AMOUNT_LABEL_DESCRIPTION')}
                                    onChangeText={(montant) => {
                                        this.setState({montant});
                                        this.isMontantValid();
                                    }}
                                />
                                {
                                    (!this.isMontantValid.isValid) &&
                                    <Text
                                        style={{color: 'red', marginTop: 2}}>{this.isMontantValid().errorMessage}</Text>
                                }
                                {
                                    (this.state.isSubmitClick && this.state.montant.length === 0) &&
                                    <Text
                                        style={{color: 'red', marginTop: 2}}>{I18n.t('PLEASE_ENTER_THE_AMOUNT')}</Text>
                                }
                            </View>

                            <View style={{marginTop: 10, marginRight: 20, marginLeft: 20, marginBottom: 10}}>
                                <OutlineTextInput
                                    borderBottomColor={(this.state.isSubmitClick && this.state.password.length === 0) ? 'red' : 'black'}
                                    value={this.state.password}
                                    secureTextEntry={true}
                                    label={I18n.t('PASSWORD')}
                                    style={{marginTop: 10}}
                                    placeholder={I18n.t('PLEASE_ENTER_THE_PASSWORD')}
                                    onChangeText={(password) => {
                                        this.setState({password});
                                        this.isMontantValid();
                                    }}
                                />
                                {
                                    (this.state.isSubmitClick && this.state.password.length === 0) &&
                                    <Text
                                        style={{
                                            color: 'red',
                                            marginTop: 2
                                        }}>{I18n.t('PLEASE_ENTER_CORRECT_PASSWORD')}</Text>
                                }
                            </View>


                            <View style={{margin: 10}}>
                                <CustomButton loading={this.props.loading} outline onPress={() => this.onPayBill()}>
                                    {I18n.t('VALIDATE')}
                                </CustomButton>
                            </View>

                        </ScrollView>


                    </View>

                </View>
            </Provider>
        );
    }

}

const mapStateToProps = state => ({
    loading: state.payBillReducer.loading,
    result: state.payBillReducer.result,
    error: state.payBillReducer.error,
});

const mapDispatchToProps = dispatch => bindActionCreators({
    payBillAction,
    payBillReset,
}, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(PaiementFacture);

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Color.containerBackgroundColor
    },
});