/* eslint-disable react-native/no-inline-styles */
/* eslint-disable prettier/prettier */
import React, {Component} from 'react';
import {Alert, Image, ProgressBarAndroid, ScrollView, StatusBar, StyleSheet, Text, View} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import {deleteUser, readUser} from './../../webservice/AuthApi';
import {getAgentNetworksList} from './../../webservice/NetworkApi';
import {responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';
import MapView, {Marker} from 'react-native-maps';
import * as Utils from '../../utils/DeviceUtils';
import CardView from 'react-native-cardview';
import I18n from 'react-native-i18n';
import {IlinkEmitter} from '../../utils/events';
import {Card, CardAction, CardButton, CardContent, CardTitle} from 'react-native-material-cards';
import {Color} from '../../config/Color';
import Fontisto from 'react-native-vector-icons/Fontisto';

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

require('./../../utils/Translations');
const height = responsiveHeight(100) - 250;
/*
var Fabric = require('react-native-fabric');
var { Crashlytics } = Fabric;*/
export default class UserAccount extends Component {
    static navigatorStyle = {
        navBarHidden: false,
        navBarBackgroundColor: theme.primaryDark,
        navBarTextColor: 'white',
        navBarButtonColor: 'white',
        drawUnderStatusBar: false,
        statusBarColor: theme.primaryDarkAdvanced,
        statusBarTextColorScheme: 'light',
    };
    static navigationOptions = ({navigation}) => {
        return {
            headerTitle: I18n.t('USER_ACCOUNT'),
            headerStyle: {
                backgroundColor: theme.primary,
                paddingTop: 10,
            },
            headerTitleStyle: {
                color: 'white',
            },
            drawerIcon: ({tintColor}) => (
                <Icon
                    name={'person'}
                    size={24}
                />
            ),
        };
    };

    static options(passProps) {
        return {
            topBar: {
                drawBehind: false,
                visible: true,
                animate: true,
                buttonColor: 'white',
                background: {
                    color: theme.primaryDark,
                },
                rightButtons: [],
            },
            backButton: {
                visible: true,
                color: 'white',
            },
            buttonColor: 'white',
            background: {
                color: theme.primaryDark,
            },
            statusBar: {
                drawBehind: false,
                visible: true,
            },
        };
    }

    constructor(props) {
        super(props);
        this.state = this.initState();
        IlinkEmitter.on('langueChange', this.updateLangue.bind(this));
        readUser().then((user) => {
            if (user !== null) {
                this.setState({user: user});

                this.updateContent(user);
            }
        });


    }

    updateLangue() {

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

    updateContent(user) {
        getAgentNetworksList(user.agentId).then((networks) => {
            console.log('networks', networks.networks);
            if (networks.success !== undefined) {
                this.setState({mynetworks: networks.networks});
            }

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

    initState() {
        return {
            user: {},
            mynetworks: [],
        };


    }

    render() {

        let cat = '';

        const {user} = this.state;

        if (user.category !== undefined || user.category !== null)
            {cat = user.category === 'super' ? I18n.t('ADMIN') : user.category === 'hyper' ?
                I18n.t('SUPER_ADMIN') : user.category === 'geolocated' ?
                    I18n.t('GEOLOCATED') : I18n.t('SIMPLE_USER');}
        return (
            <View style={styles.container}>
                <StatusBar
                    backgroundColor={theme.primaryDark}
                    barStyle="light-content"
                    translucent={false}
                />
                <ScrollView style={{
                    flex: 1,
                    marginTop: -5,
                }}>
                    <View style={styles.userInformation}>
                        <ScrollView>
                            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                                <Image source={require('./../../datas/img/users/man.png')}
                                       style={{width: 92, height: 92}}/>
                            </View>
                            <View style={{flex: 1, flexDirection: 'row'}}>
                                {user.category === undefined || user.category === null ?
                                    this.getHeaderLeftProfil(user) : this.getHeaderLeftAgentProfil(user)
                                }
                                <View style={{flex: user.category === undefined || user.category === null ? 2 : 2}}>
                                    <Text style={styles.textInformation}>{this.state.user.firstname}</Text>
                                    <Text style={styles.textInformation}>{this.state.user.lastname}</Text>
                                    {<Text style={{
                                        color: 'white',
                                        fontSize: 17,
                                        fontWeight: 'bold',
                                        textAlign: 'center',
                                    }}>{cat}</Text>
                                    }

                                </View>
                                {user.category === undefined || user.category === null ?
                                    this.getHeaderRight(user)
                                    : this.getHeaderRightAgent(user)}

                            </View>
                        </ScrollView>

                    </View>
                    <View style={styles.networkInformation}>

                        <Text style={{
                            marginLeft: 10, marginRight: 10, marginTop: 15, marginBottom: 5, fontSize: 17,
                            fontWeight: 'bold', color: 'black',
                        }}>{I18n.t('ACCOUNT_INFO')}</Text>
                        <CardView style={{marginLeft: 10, marginRight: 10, paddingBottom: 20}}>
                            <ScrollView>
                                {user.category !== undefined && user.category !== null ? this
                                    .addAgentInformation(user) : null}
                                <Text style={styles.textInformation2}>
                                    <Icon name={'location-on'} size={18}/>{'  ' + this.state.user.country}</Text>

                                {user.balance !== undefined && user.balance !== null ? this.showBalance(user) : null}
                                <Text style={styles.textInformation2}>
                                    <Icon name={'mail'} size={18}/>{'  ' + this.state.user.email}</Text>


                                <Text style={styles.textInformation2}>

                                    <Icon name={'phone'} size={18}/>
                                    {'  ' + this.state.user.phone}</Text>
                                {this.showPhoneSup()}
                                <Text style={styles.textInformation2}>

                                    <Icon name={'account-balance-wallet'} size={18}/>
                                    {'  ' + this.state.user.network}</Text>
                            </ScrollView>
                        </CardView>

                        {user.category === 'geolocated' ?
                            (<Text style={{
                                marginLeft: 10,
                                marginRight: 10,
                                marginTop: 15,
                                marginBottom: 5,
                                fontSize: 17,
                                fontWeight: 'bold',
                                color: 'black',
                            }}>{I18n.t('MY_NETWORK')}</Text>)

                            : null}
                        {user.category === 'geolocated' ? (this.state.mynetworks.length > 0 ? this.state.mynetworks.map(item => this.generateItemNetwork(item)) : this.showLoader()) : null}
                    </View>
                </ScrollView>

            </View>
        );
    }

    showPhoneSup() {
        if (this.state.user.phoneTransaction != undefined && this.state.user.phoneTransaction != null) {

            return (<Text style={styles.textInformation2}>

                    <Icon name={'phone'} size={18}/>
                    {'  ' + this.state.user.phoneTransaction}</Text>
            );
        }
    }

    getHeaderLeftProfil(user) {
        return (<View style={{flex: 2}}>
            <Text style={{
                color: 'white',
                fontSize: 15,
                fontWeight: 'bold',
                textAlign: 'center',
            }}>{I18n.t('NETWORK')}</Text>
            <Text style={{color: 'white', fontSize: 15, textAlign: 'center'}}>{user.network}</Text>
        </View>);
    }

    getHeaderRight(user) {
        return (<View style={{flex: 0}} />);
    }

    getHeaderRightAgent(user) {

        return (<View style={{flex: 2}}>
            <Text style={{
                color: 'white',
                fontSize: 15,
                textAlign: 'center',
                fontWeight: 'bold',
            }}>{I18n.t('MEMBER_CODE')}</Text>
            <Text style={{color: 'white', fontSize: 13, textAlign: 'center'}}>{user.code_membre}</Text>
        </View>);

    }

    getHeaderLeftAgentProfil(user) {
        return (<View style={{flex: 2}}>
            <Text style={{
                color: 'white',
                fontSize: 15,
                fontWeight: 'bold',
                textAlign: 'center',
            }}>{I18n.t('NETWORK')}</Text>
            <Text style={{color: 'white', fontSize: 13, textAlign: 'center'}}>{user.network}</Text>
        </View>);
    }

    addAgentInformation(user) {
        console.log(user);
        if (user.category === 'geolocated') {
            (<View>
                <Text style={{marginLeft: 10, marginTop: 10, color: theme.primaryDark}}>
                    <Icon name={'code'} size={18} color={theme.primaryDark} style={{paddingRight: 10}}/>
                    {' ' + user.code_parrain}</Text>
            </View>);

        } else
            {return (<View>

                <Text style={{marginLeft: 10, marginTop: 10, color: theme.primaryDark}}>
                    <Icon name={'code'} size={18} color={theme.primaryDark} style={{paddingRight: 10}}/>
                    {' ' + user.code_parrain}</Text>
                <View style={{
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    width: responsiveWidth(90),
                    marginRight: 50,
                }}>
                    <Text style={{marginLeft: 12, marginTop: 10, color: theme.primaryDark}}>
                        <Icon name={'group-work'} color={theme.primaryDark} size={18}/>
                        {'  ' + ((user.nbre_reseau === null || user.nbre_reseau === undefined) ? 0 : user.nbre_reseau) + ' ' + I18n.t('FREE')}
                    </Text>
                    <Text style={{marginLeft: 12, marginTop: 10, color: theme.primaryDark}}>
                        <Icon name={'book'} color={theme.primaryDark}
                              size={18}/>{'  ' + ((user.nbre_reseau === null || user.nbre_membre === undefined) ? 0 : user.nbre_membre) + ' ' + I18n.t('SAVED')}
                    </Text>
                </View>
            </View>);}
    }

    mapUser(user) {
        const myPosition = {latitude: parseFloat(user.latitude), longitude: parseFloat(user.longitude)};

        return (<MapView
                liteMode
                ref={(ref) => {
                    this.mapRef = ref;
                }}
                style={styles.map}
            >
                {this.state.myPosition !== undefined ?
                    <Marker
                        title={'Vous êtes ici'}
                        minZoomLevel={10}
                        coordinate={{longitude: myPosition.longitude, latitude: myPosition.latitude}}
                    /> :
                    null}
            </MapView>
        );
    }

    showBalance(user) {
        return <Text style={styles.textInformation2}>
            <Icon name={'folder'} size={18}/>{'  ' + this.state.user.balance + ' '}</Text>;

    }

    makeGeolocatedNetworkList() {

        return (<View>
            <Text style={{
                marginLeft: 10,
                marginRight: 10,
                marginTop: 15,
                marginBottom: 5,
                fontSize: 17,
                fontWeight: 'bold',
                color: 'black',
            }}>Mes reseaux</Text>

        </View>);
    }

    generateItemNetwork(item) {
        return (

            <Card>

                <CardTitle
                    title={item.name}
                    subtitle={item.phone}
                />
                <CardContent>
                    <View Style={{flex: 1}}>
                        <Text style={styles.textInformation2}>
                            <Icon name={'code'} size={18}/>{'  ' + item.code_membre + ' '}</Text>
                        <Text style={styles.textInformation2}>
                            <Icon name={'people'} size={18}/>{'  ' + item.code_parrain + ' '}</Text>
                        {item.provider_class !== null && (
                            <>
                                <Text style={styles.textInformation2}>
                                    <Fontisto name={'doctor'} size={18}/>{'  ' + item.provider_class + ' '}</Text>
                            </>

                        )}

                    </View>
                </CardContent>
                <CardAction
                    separator={true}
                    inColumn={false}>
                    <CardButton
                        onPress={() => {
                            Alert.alert(
                                I18n.t('TITLE_SUPPRESS_CONFIRM'),
                                I18n.t('TEXT_SUPPRESS_CONFIRM'),
                                [
                                    {
                                        text: I18n.t('NO'), onPress: () => {
                                        },
                                    },
                                    {
                                        text: I18n.t('YES'), onPress: () => {
                                            deleteUser(item).then(() => {
                                                this.setState({isLoading: true});
                                                this.updateContent(this.state.user);
                                            });
                                        },
                                        style: 'cancel',
                                    },
                                ],
                            );
                        }}
                        title={I18n.t('DELETE_GEOLOCATED_USER')}
                        color="crimson"
                    />
                </CardAction>
            </Card>);
    }

    showLoader() {
        return (<View style={{height: responsiveHeight(20)}}><ProgressBarAndroid

            style={{justifyContent: 'center', alignItems: 'center'}}
        /></View>);
    }
}

const styles = StyleSheet.create({
    userInformation: {
        backgroundColor: theme.primary,
        flex: 1,
        justifyContent: 'center',
        paddingTop: responsiveHeight(2),
        paddingBottom: responsiveHeight(5),
    },
    map: {
        height: 200,
        marginRight: responsiveWidth(5),
        marginLeft: responsiveWidth(5),
        marginVertical: 10,
    },
    networkInformation: {
        width: responsiveWidth(100),
        backgroundColor: '#EEEEEE',
        flex: 1,
    },
    container: {
        flex: 1,
        backgroundColor: '#EEEEEE',
    },
    contain: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    identificationOptionMenuContainer: {
        flexDirection: 'row',
        paddingTop: 10,
        paddingLeft: 10,
        paddingRight: 10,
    },
    containerTouch: {
        flex: 1,
        flexDirection: 'row',
        marginRight: 2.5,
        alignItems: 'center',
        shadowColor: Color.borderColor,
        borderColor: Color.borderColor,
        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: 5,
    },
    textInformation: {
        fontSize: 16,
        color: 'white',
        textAlign: 'center',
    },
    textInformation2: {
        fontSize: 15,
        marginTop: 7,
        color: theme.primaryDark,
        marginLeft: 10,
    },
    textTitle: {
        fontSize: 25,
        color: 'white',
        fontWeight: 'bold',
    },

    textTitle2: {
        fontSize: 25,
        color: theme.primaryDark,
        fontWeight: 'bold',
    },
});
