import React, {Component} from 'react';
import {
    ActivityIndicator,
    Image,
    Platform,
    ProgressBarAndroid,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    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 {Typography} from '../../config/typography';
import * as Utils from '../../utils/DeviceUtils';
import {IlinkEmitter} from "../../utils/events";
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import {getBankListAction, getBankListReset} from "../../webservice/BankApi";
import {store} from "../../redux/store";
import {readUser} from "../../webservice/AuthApi";
import {getOperatorListAction, getOperatorListReset} from "../../webservice/WalletApi";

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

class OperateurOptionSelect extends Component {

    constructor(props) {
        super(props);
        IlinkEmitter.on("langueChange", this.updateLangue.bind(this));
        console.log("OPERATEUR OPTION PROPS", this.props);
        this.state = {
            options: this.props.navigation.state.params.optionSelect.options,
            title: this.props.navigation.state.params.optionSelect.title,
            subTitle: this.props.navigation.state.params.optionSelect.subTitle,
            operatorType: this.props.navigation.state.params.optionSelect.operatorType,
            wallet: store.getState().walletDetailReducer.result.response
        }
        this.props.getBankListReset();
        this.props.getOperatorListReset();

        readUser().then((user) => {
            if (user) {
                if (user !== undefined) {
                    if (this.state.options.length > 0) {
                        if (user.category === undefined)
                            this.props.getOperatorListAction(this.state.operatorType, this.state.wallet.id_wallet_network)
                        else {
                            if (user.category === 'geolocated')
                                this.props.getOperatorListAction(this.state.operatorType, this.state.wallet.id_network)
                        }
                    } else {
                        if (user.category === undefined) {

                            this.props.getOperatorListAction('bank', this.state.wallet.id_wallet_network)
                        } else {
                            if (user.category === 'geolocated')
                                this.props.getOperatorListAction('bank', this.state.wallet.id_network)
                        }
                    }

                    this.setState({user});
                }
            }
        });

    }

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

    redirectToRoute = (item) => {

        console.log("Item selected", item);
        if (this.state.options.length > 0) {

            this.props.navigation.push(this.state.options[0].screen, {
                title: item.operator_name,
                type: this.state.options[0].type,
                operator_id: item.id_operator,
                typeOperator: this.state.operatorType
            });
        } else {
            if (this.state.user.category === 'geolocated')
                this.props.navigation.navigate(route.envoieWalletToBankAgent, {bank: item});
            else
                this.props.navigation.navigate(route.envoieWalletToBankUser, {bank: item});
        }
    }

    renderLoader = () => {
        return (
            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                {Platform.OS === 'android'
                    ?
                    (
                        <>
                            <ProgressBarAndroid/>
                            <Text>{I18n.t('LOADING_DOTS')}</Text>

                        </>
                    ) :
                    <>
                        <ActivityIndicator size="large" color={'#ccc'}/>
                        <Text>{I18n.t('LOADING_DOTS')}</Text>
                    </>
                }
            </View>
        )
    }

    renderItem = (item, index) => {
        return (

            <TouchableOpacity
                key={index}
                style={[styles.paymentItem, {borderBottomColor: Color.borderColor}]}
                onPress={() => {
                    this.redirectToRoute(item);
                }}>
                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <View>
                        <Text style={Typography.body1}>{item.operator_name}</Text>
                        <Text style={[Typography.footnote, Color.grayColor]} style={{marginTop: 5}}>
                            {I18n.t('COUNTRY')}: {`${item.operator_address}, ${item.country}`}
                        </Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    renderBankList = () => {

        const {result, error} = this.props;
        if (error !== null) {
            if (typeof error.data !== 'undefined') {
                return (
                    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                        <Text style={Typography.body1}>{error.data.error}</Text>
                    </View>
                )
            } else {
                return (
                    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                        <Text style={Typography.body1}>{error}</Text>
                    </View>
                )
            }
        }
        if (result !== null) {
            if (result.response !== null) {
                return (
                    Array.isArray(result.response) && (result.response.length) > 0 ?
                        (<ScrollView style={{flex: 1, padding: 20}}>
                            {
                                result.response.map((item, index) => (
                                    this.renderItem(item, index)
                                ))
                            }
                        </ScrollView>) :
                        (
                            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                                <Text style={Typography.body1}>{I18n.t('NO_OPERATOR_AVAILABLE')}</Text>
                            </View>
                        )
                )
            }
        }

    }

    renderItemElement = (item, index) => {

        return (
            <TouchableOpacity
                key={index}
                style={[styles.paymentItem, {borderBottomColor: Color.borderColor}]}
                onPress={() => {
                    this.props.navigation.navigate(item.screen, {
                        type: item.type,
                        title: item.title
                    })
                }}>

                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <View style={styles.iconContent}>
                        <Image style={{width: 48, height: 48}} source={{uri: item.icon}}/>
                    </View>
                    <View>
                        <Text style={Typography.body1}>{item.title}</Text>
                        <Text style={Typography.footnote}>{item.title}</Text>
                    </View>
                </View>

            </TouchableOpacity>
        )
    }

    renderList = () => {

        const {options} = this.state;

        return (
            <ScrollView style={{flex: 1, padding: 20}}>
                {
                    options.map((item, index) => (
                        this.renderItemElement(item, index)
                    ))
                }
            </ScrollView>
        );
    }


    render() {
        console.log("OPERATEUR OPTION STATE", this.state.options.length);
        return (
            <Provider>
                <View style={{flex: 1}}>

                    <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={I18n.t(this.state.title)}
                            subtitle={I18n.t(this.state.subTitle)}
                        />
                    </Appbar.Header>

                    <View style={styles.container}>

                        {
                            this.props.loading ?
                                this.renderLoader() :
                                this.props.result != null ?
                                    this.renderBankList() :
                                    null
                        }

                    </View>

                </View>
            </Provider>
        );
    }
}

const mapStateToProps = state => ({
    loading: state.getListOperatorReducer.loading,
    result: state.getListOperatorReducer.result,
    error: state.getListOperatorReducer.error,


});

const mapDispatchToProps = dispatch => bindActionCreators({
    getBankListAction,
    getBankListReset,
    getOperatorListAction,
    getOperatorListReset
}, dispatch);

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

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    paymentItem: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        borderBottomWidth: 1,
        paddingVertical: 5,
        width: "100%",
        marginBottom: 15
    },
    iconContent: {
        width: 60,
        marginRight: 10,
        alignItems: "center"
    },
    item: {
        paddingVertical: 15,
        borderBottomWidth: 1,
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center"
    },
    /*      item: {
              paddingVertical: 15,
              borderBottomWidth: 1,
              flexDirection: "row",
              justifyContent: "space-between",
              alignItems: "center"
         }, */
    lottie: {
        width: 540,
        height: 240
    },
    checkDefault: {
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        borderBottomWidth: 1,
        paddingVertical: 10,
        marginTop: 5
    },
    transactionContainer: {
        flexDirection: 'row',
        paddingTop: 10,
    },
    containerTouch: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        shadowColor: Color.borderColor,
        borderColor: Color.borderColor,
        borderWidth: 0.5,
        shadowOffset: {width: 1.5, height: 1.5},
        shadowOpacity: 1.0,
        elevation: 5,
        borderRadius: 10,
        backgroundColor: Color.cardBackgroundColor
    },

    contain: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    imageBanner: {
        marginTop: 15,
        marginLeft: 5,
        width: Utils.scaleWithPixel(30),
        height: Utils.scaleWithPixel(30)
    },
    content: {
        height: Utils.scaleWithPixel(60),
        paddingHorizontal: 10,
        justifyContent: 'space-between',
        alignItems: 'flex-start',
        flex: 1,
    },
    contentTitle: {
        paddingTop: 12,
    }

});