import LottieView from 'lottie-react-native'; // if you have "esModuleInterop": true
import 'moment/locale/en-au';
import 'moment/locale/en-ca';
import 'moment/locale/en-gb';
import 'moment/locale/en-ie';
import 'moment/locale/en-il';
import 'moment/locale/en-nz';
import 'moment/locale/es-us';
import 'moment/locale/fr';
import React from 'react';
import {
    Platform,
    ProgressBarAndroid,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    ActivityIndicator,
    View
} from 'react-native';
import DeviceInfo from 'react-native-device-info';
import I18n from "react-native-i18n";
import Icon from 'react-native-vector-icons/MaterialIcons';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {Color} from '../../config/Color';
import {Typography} from '../../config/typography';
import {readUser} from '../../webservice/AuthApi';
import {getNotificationAction, getNotificationReset} from '../../webservice/OnesignalApi';
import BaseScreen from './../BaseScreen';

const theme = require('./../../utils/theme.json');
let moment = require('moment-timezone');

class Notifications extends BaseScreen {
    static navigatorStyle = {
        navBarBackgroundColor: theme.primaryDark,
        navBarTextColor: 'white',
        statusBarBackgroundColor: theme.primaryDarkAdvanced,
        navBarButtonColor: 'white',
        statusBarTextColorScheme: 'light',
    };
    static navigationOptions = {
        headerTitle: I18n.t('NOTIFICATIONS'),
        drawerIcon: ({tintColor}) => (
            <Icon
                name={'notifications-active'}
                size={24}
            />
        ),
    };

    constructor(props) {
        super(props);
        this.currentLocale = I18n.locale.includes("fr") ? "fr" : "en-gb";
        moment.locale(this.currentLocale);

    }

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

    componentDidMount() {

        readUser().then((user) => {
            if (user) {
                if (user !== undefined) {
                    if (user.category !== undefined) {
                        if (user.category === "super" || user.category === "geolocated" || user.category === "hyper") {
                            this.props.getNotificationAction({
                                agent_code: user.code_membre
                            });
                        }
                    } else {
                        this.props.getNotificationAction({
                            user_code: user.user_code
                        });
                    }
                }
            }
        });

    }

    getCreationDateToHumanFormat = (date) => {
        let re = moment.tz(date, moment.tz.guess()).format();
        console.log("Human date", moment(re).fromNow());
        return moment(re).fromNow();
    }

    getNotificationTypeIcon = (notification) => {
        switch (notification) {
            case 'creation':
                return 'account-multiple-plus';
            case 'demandeSuppressionGroupe':
                return 'account-multiple-minus';
            case 'adhesion':
                return 'account-multiple-check'
            case 'nano_credit':
                return 'cash'
            default:
                return 'account-multiple'
        }
    }

    getDemandTypeColor = (type) => {
        switch (type) {
            case 'creation':
                return 'green';
            case 'suppression':
                return 'red';
            case 'adhesion':
                return Color.primaryColor
            case 'nano_credit':
                return Color.primaryColor
            default:
                return Color.primaryColor
        }
    }


    renderNotificationItem = (item) => {
        return (

            <TouchableOpacity
                key={item.id}
                style={[styles.paymentItem, {borderBottomColor: Color.borderColor}]}
                onPress={() => {
                    switch (item.data.screen) {
                        case 'historyItemDetails':
                            this.props.navigation.navigate(item.data.screen, {
                                item: item.data.data
                            });
                            break;

                        default:
                            this.props.navigation.navigate(item.data.screen, {
                                id: item.data.data.id
                            });
                            break;
                    }

                }}>
                <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.message}</Text>
                        <Text style={[Typography.footnote, Color.grayColor]} style={{marginTop: 5}}>
                            {this.getCreationDateToHumanFormat(item.date)}
                        </Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    renderNotificationList = () => {

        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.renderNotificationItem(item)
                                ))
                            }
                        </ScrollView>) :
                        (
                            <View style={{justifyContent: "center", alignItems: 'center', marginTop: 100}}>

                                <LottieView
                                    style={styles.lottie}
                                    source={require("./../../datas/json/781-no-notifications.json")}
                                    autoPlay
                                    loop
                                />
                                <Text style={styles.text}>{I18n.t('NO_NOTIFICATION')}</Text>
                            </View>
                        )
                )
            }
        }

    }

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

    render() {
        return (
            <View style={styles.container}>
                <StatusBar
                    backgroundColor="#00000030"
                    barStyle="light-content"
                    translucent={false}
                />

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

            </View>)
    }
}

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

const mapDispatchToProps = dispatch => bindActionCreators({
    getNotificationAction: getNotificationAction,
    getNotificationReset: getNotificationReset
}, dispatch);

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

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'
    },
    text: {
        fontSize: 17,
        fontWeight: 'bold',
    },
    lottie: {
        width: 248,
        height: 248
    },
    paymentItem: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        borderBottomWidth: 1,
        paddingVertical: 5,
        width: "100%",
        marginBottom: 15
    },
    iconContent: {
        width: 60,
        marginRight: 10,
        alignItems: "center"
    }
})
