import React, {Component} from 'react';
import {Alert, Image, ScrollView, StatusBar, StyleSheet, Text, View} from 'react-native';
import {Fumi} from 'react-native-textinput-effects';
import I18n from 'react-native-i18n'
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome5'
import Icon from 'react-native-vector-icons/FontAwesome5'
import {AssignAgentGeo, getCodeInformation} from './../../webservice/AuthApi';
import {responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';
import Button from 'apsl-react-native-button'
import {IlinkEmitter} from "../../utils/events";
import {Dropdown} from "react-native-material-dropdown-v2";

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

/*var Fabric = require('react-native-fabric');

var { Crashlytics } = Fabric;
var { Answers } = Fabric;*/
export default class AddNetwork extends Component {
    static navigatorStyle = {
        navBarBackgroundColor: theme.primaryDark,
        navBarTextColor: 'white',
        navBarButtonColor: 'white',
        drawUnderStatusBar: false,
        statusBarColor: theme.primaryDarkAdvanced,
        statusBarTextColorScheme: 'light',
    };
    static navigationOptions = ({navigation}) => {
        return {
            drawerLabel: navigation.getParam("name", I18n.t('ADD_NETWORK')),
            drawerIcon: ({tintColor}) => (
                <Icon
                    name={'user'}
                    size={24}
                />
            ),
        }
    };

    updateLangue() {

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

    static options(passProps) {
        return {
            topBar: {
                title: {
                    text: "",
                },
                backButton: {
                    visible: true,
                    color: "white"
                },
                buttonsRight: [],
                buttonColor: "white",
                background: {
                    color: theme.primaryDark
                }
            }
        }
    }

    constructor(props) {
        super(props)
        this.state = this.generateState()
        IlinkEmitter.on("langueChange", this.updateLangue.bind(this))
    }


    generateState() {
        return {
            isLoading: false,
            notifi: false,
            isNanoSante: false,
            provider_classes: [],
            provider_class: null
        }
    }

    render() {
        return (
            <View style={style.container}>
                <StatusBar
                    backgroundColor="#00000030"
                    barStyle="light-content"
                    translucent={true}
                />
                <ScrollView style={{flex: 1, paddingTop: 30}}>
                    <View style={style.appContainer}>
                        <Image source={require('./../../datas/img/icon3.png')}
                               style={{width: responsiveWidth(90), resizeMode: "contain"}}/>
                    </View>
                    <Text style={style.title}>{I18n.t('ADD_NETWORK')}</Text>
                    <Fumi iconClass={FontAwesomeIcon}
                          iconName={"code"}
                          labelStyle={style.labelInput}
                          inputStyle={{color: 'black'}}
                          value={this.state.validateCode}
                          label={I18n.t('SPONSOR_CODE')}
                          onChangeText={(text) => this.setState({validateCode: text})}
                          style={style.input}/>

                    <Fumi
                        label={I18n.t('PHONE')}
                        iconClass={FontAwesomeIcon}
                        iconName={'phone'}
                        iconColor={'white'}
                        style={style.input}
                        autoCapitalize={'none'}
                        keyboardType={"phone-pad"}
                        autoCorrect={false}
                        value={this.state.enterPhone}
                        inputStyle={{color: 'black'}}
                        ref={(com) => {
                            this.numberRef = com
                        }}
                        onChangeText={(text) => this.setState({enterPhone: text})}
                        labelStyle={style.labelInput}
                    />


                    {this.state.provider_classes.length >= 1 && <View
                        style={{
                            width: responsiveWidth(90),
                            marginTop: 20,
                            alignSelf: 'center',
                            borderRadius: 10,
                            paddingLeft: 20,
                            paddingRight: 20,
                            backgroundColor: 'white'
                        }}>
                        <Dropdown
                            label={I18n.t('CLASSE_PRESTATAIRE')}
                            data={this.state.provider_classes}
                            useNativeDriver={true}
                            value={this.state.provider_class === null ? "" :
                                this.state.provider_class}
                            onChangeText={(value, index, data) => {
                                console.log("Value", value);
                                this.setState({provider_class: value});
                            }}
                            valueExtractor={(value) => {
                                return value
                            }}
                            labelExtractor={(value) => {
                                return value.name
                            }}
                        />
                    </View>}

                    <Button style={style.btnStyle} textStyle={style.btnTextStyle}
                            isLoading={this.state.isLoading} onPress={() => this.validateNetwork()}
                    >{I18n.t('VALIDATE')}</Button>
                </ScrollView>

            </View>)
    }

    async validateNetwork() {

        const {validateCode, isLoading, enterPhone} = this.state;

        if (validateCode !== undefined && validateCode !== null && enterPhone !== null) {
            this.setState({isLoading: true});
            let codeInformation = await getCodeInformation(validateCode);

            if (codeInformation) {
                console.log("codeInformation", codeInformation);
                if (codeInformation.hasOwnProperty('provider_classes')) {
                    if (this.state.provider_classes.length >= 1)
                        await this.submitNetwork();
                    this.setState({provider_classes: codeInformation.provider_classes});
                    this.setState({isLoading: false});
                } else {
                    await this.submitNetwork();
                }
            }

        }
    }

    async submitNetwork() {
        const {validateCode, isLoading, enterPhone} = this.state;

        let res = await AssignAgentGeo(validateCode, enterPhone, this.state.provider_class !== null ? this.state.provider_class.id : null);
        this.setState({isLoading: false});
        if (res) {
            if (res['success'] !== undefined) {
                Alert.alert(
                    I18n.t('ADD_SUCCES'),
                    I18n.t('ADD_SUCCESS_TEXT')
                    , [
                        {
                            text: 'OK', onPress: () => {
                                this.setState({validateCode: "", enterPhone: "", provider_classes: [], provider_class: null})
                            }
                        }
                    ])
            } else {

                if (res['error']) {
                    let error = res["error"];
                    Alert.alert("Une erreur est survenu",
                        res["error_msg"]
                        , [{
                            text: "Ok", onPress: () => {
                            }
                        }]);
                } else {
                    if (res['error']) {
                        let error = res["error"];
                        Alert.alert("Une erreur est survenu",
                            "Verifier que les champs sont bien rempli"
                            , [{
                                text: "Ok", onPress: () => {
                                }
                            }]);
                    }
                }
            }
        }
    }
}
const style = StyleSheet.create({
    btnHelpText: {
        color: 'white',
        fontWeight: 'bold'
    },
    btnHelp: {
        width: responsiveWidth(10),
        marginTop: responsiveHeight(10),
        alignSelf: 'flex-end',
        marginRight: 20,
        borderColor: 'transparent',
        backgroundColor: theme.primaryDark
    },
    btnTextStyle: {
        color: "white",
        fontWeight: 'bold',
    },
    btnStyle: {
        alignSelf: 'center',
        width: responsiveWidth(95),
        marginTop: 20,
        borderColor: 'transparent',
        backgroundColor: theme.primaryDarkAdvanced,
        height: responsiveHeight(8)

    },
    appContainer: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
    container: {
        alignItems: 'center',
        justifyContent: 'center',
        alignSelf: 'center',
        flex: 1,
        width: responsiveWidth(100),
        height: responsiveHeight(100),
        backgroundColor: theme.primary
    },
    input: {
        height: responsiveHeight(10),
        width: responsiveWidth(90),
        borderRadius: 10,
        marginTop: 20,
        color: "black"
    },
    logo: {
        width: 128,
        height: 128
    },
    nameApp: {
        fontSize: 27,
        fontWeight: 'bold',
        color: 'white'
    },
    title: {
        fontSize: 22,
        fontWeight: 'bold',
        margin: 10,

        color: 'white'
    },
    subtitle: {
        fontSize: 20,
        margin: 10,
        color: 'white'
    }
})
