import React, {Component} from 'react';
import {
    ActivityIndicator,
    Image,
    Platform,
    ProgressBarAndroid,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import I18n from 'react-native-i18n'
import {Color} from '../../config/Color';
import {baseUrl} from '../../webservice/IlinkConstants';
import {IlinkEmitter} from "../../utils/events";
import {Appbar, Provider} from 'react-native-paper';
import {getWalletActivated} from '../../webservice/WalletApi';
import {connect} from 'react-redux';
import {readUser} from '../../webservice/AuthApi';
import {bindActionCreators} from 'redux';
import {Typography} from '../../config/typography';

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

class WalletSelect extends Component {

    constructor(props) {
        super(props);
        slugify.extend({'+': 'plus'});
        IlinkEmitter.on("langueChange", this.updateLangue.bind(this));
        this.state = {
            result: null,
            isDataLoaded: false,
            agentId: null
        }

    }

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

    componentDidMount() {

        readUser().then((user) => {
            if (user) {
                if (user !== undefined) {
                    if (user.phone !== undefined) {
                        this.props.getWalletActivated(user.agentId);
                        this.setState({agentId: user.agentId});
                    }
                }
            }
        });

    }

    /*      refresh() {
              readUser().then((user) => {
                   if (user) {
                        if (user !== undefined) {
                             if (user.phone !== undefined) {
                                  this.props.getWalletActivated(user.agentId);
                                  this.setState({ agentId: user.agentId });
                             }
                        }
                   }
              });
         } */

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

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

    renderWalletItem = (item) => {
        let icon = `${baseUrl}/datas/img/network/${slugify(item.network, {lower: true})}-logo.png`;
        let itemToSend = item;
        itemToSend.agentId = this.state.agentId;
        return (

            <TouchableOpacity
                key={item.id}
                style={[styles.paymentItem, {borderBottomColor: Color.borderColor}]}
                onPress={() => this.props.navigation.navigate('walletDetail', {
                    wallet: itemToSend,/*
                         onRefreshDetail: () => this.refresh() */
                })}>
                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <View style={styles.iconContent}>
                        <Image style={{width: 48, height: 48}} source={{uri: icon}}/>
                    </View>
                    <View>
                        <Text style={Typography.body1}>{item.network}</Text>
                        <Text style={[Typography.footnote, Color.grayColor, {marginTop: 5}]}>
                            {I18n.t('COUNTRY')}: {item.country}
                        </Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    renderWalletList = () => {

        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) => (
                                    this.renderWalletItem(item)
                                ))
                            }
                        </ScrollView>) :
                        (
                            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                                <Text style={Typography.body1}>{I18n.t('NO_WALLET_ACTIVED')}</Text>
                            </View>
                        )
                )
            }
        }

    }

    render() {
        console.log("WALLET PROPS", this.props);
        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('WALLET')}
                            subtitle={I18n.t('SELECT_YOUR_WALLET')}
                        />
                    </Appbar.Header>

                    {
                        this.props.loading ?
                            this.renderLoader() :
                            this.renderWalletList()
                    }


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


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

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


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

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Color.containerBackgroundColor,
    },
    paymentItem: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        borderBottomWidth: 1,
        paddingVertical: 5,
        width: "100%",
        marginBottom: 15
    },
    iconContent: {
        width: 60,
        marginRight: 10,
        alignItems: "center"
    }
});