import React from 'react';
import {
    Animated,
    AppState,
    Platform,
    ActivityIndicator,
    ProgressBarAndroid,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import ActionButton from 'react-native-action-button';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {responsiveFontSize, responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';
import {readUser} from "../../webservice/AuthApi";
import 'moment';
import 'moment/locale/fr'
import 'moment/locale/es-us'
import 'moment/locale/en-au'
import 'moment/locale/en-ca'
import 'moment/locale/en-ie'
import 'moment/locale/en-il'
import 'moment/locale/en-nz'
import 'moment/locale/en-gb'
import moment from 'moment-timezone';
import {accent, primary, primaryDark, purpleLight} from './../../utils/theme.json';
import I18n from 'react-native-i18n'
import {Appbar, Provider} from 'react-native-paper';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {getNanoCreditDemandsAction, getNanoCreditDemandsReset} from '../../webservice/user/NanoCreditApi';
import {IlinkEmitter} from '../../utils/events';
import {Typography} from '../../config/typography';
import {ScrollView} from 'react-native-gesture-handler';
import {Color} from '../../config/Color';

let route = require('./../../route.json')

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

var sortIcons;
var sectionIcons;

require('./../../utils/Translations')


class DemandValidationGroup extends React.Component {

    constructor(props) {
        super(props, true);
        this.state = {
            user: {},
            conserve: [],
            count: 0,
            translateAnim: new Animated.Value(0),
            visibleMenu: false,
            appState: AppState.currentState,
            filter: false,
            sortIcons: null,
            panelVisible: false,
            filder_disable: true,
            datestartformated: 'La date de debut',
            dateendformated: 'La date de fin',
            datestart: null,
            dateend: null,
            isLoaded: false,
            isSectionned: false,
            isDateTimePickerVisible: false,
            isDateEndTimePickerVisible: false,
            isDataSubmit: false,
            position: 0
        };
        readUser().then((user) => {
            this.setState({user: user});
            this.props.getNanoCreditDemandsAction(user.id);
        });

        IlinkEmitter.on("langueChange", this.updateLangue.bind(this));

        this.props.getNanoCreditDemandsReset();
        this.navigation = this.props.navigation
        this.currentLocale = I18n.locale.includes("fr") ? "fr" : "en-gb";
        moment.locale(this.currentLocale);
        //IlinkEmitter.on('treatNanoGroupDemand', this.refreshData);
    };

    static navigatorStyle = {
        navBarBackgroundColor: primary,
        statusBarColor: primaryDark,
        navBarTextColor: '#FFFFFF',
        navBarButtonColor: '#FFFFFF',
        contextualMenuStatusBarColor: theme.accent,
        contextualMenuBackgroundColor: theme.accentLight,
        contextualMenuButtonsColor: '#ffffff'

    };

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

    componentDidMount() {
        const {routeName} = this.navigation.state
        this.setState({
            position: routeName === "demandeValidationGroupe" ? 0
                : routeName === "myNanoCreditGroup" ? 1
                    : 2
        });
        this.animateSlidingUp(false)

    }

    componentWillUnmount() {
        clearInterval(this.intervaller)
    }


    animateSlidingUp(state = false) {
        const height = responsiveHeight(100)
        let initialValue = !state ? 0 : height,
            finalValue = !state ? height : 0;

        this.setState({isSliding: state})

        this.state.translateAnim.setValue(initialValue);  //Step 3
        Animated.timing(     //Step 4
            this.state.translateAnim,
            {
                toValue: finalValue,
                duration: 500,
                useNativeDriver: true,
            }
        ).start()
    }

    _openMenu = () => this.setState({visibleMenu: true});

    _closeMenu = () => this.setState({visibleMenu: false});

    getDemandTypeIcon = (type) => {
        switch (type) {
            case 'creation':
                return 'account-multiple-plus';
            case 'suppression':
                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
        }
    }

    renderDemandItem = (item) => {
        let dateFormat = moment.tz(item.date_creation_demande, moment.tz.guess()).format();
        dateFormat = moment(dateFormat).fromNow();

        return (
            <TouchableOpacity onPress={() => {
                this.props.navigation.push(route.demandGroupNanoCreditDetail, {
                    id: item.id
                });
            }}
                              style={[styles.paymentItem]}>

                <View style={{flexDirection: 'row', alignItems: 'center',}}>
                    <View style={styles.iconContent}>

                        <Icon name={this.getDemandTypeIcon(item.type)} color={this.getDemandTypeColor(item.type)}
                              size={35}/>
                    </View>
                </View>
                <View style={styles.content}>

                    <Text style={styles.title}>{item.nom}</Text>

                    <Text style={styles.description}>{`${I18n.t('CREATOR')}: ${item.createur}`}</Text>

                    {/* <Text style={styles.description}>{`Sponsor 1: ${item.sponsor1}`}</Text>

                         <Text style={styles.description}>{`Sponsor 2:  ${item.sponsor2}`}</Text>

                         <Text style={styles.description}>{`Sponsor 3:  ${item.sponsor3}`}</Text> */}

                    <View style={styles.timeContent}>
                        <View style={{alignContent: 'flex-start', flex: 1, flexDirection: 'row'}}>
                            <Text style={{
                                fontWeight: 'bold',
                                marginLeft: 20,
                                marginBottom: 10,
                                color: item.nombre_validation === 3 ? 'green' : 'red',
                            }}>
                                {item.nombre_validation === 3 ? I18n.t('VALIDATE') : I18n.t('NO_VALIDATE')}
                                {` (${item.nombre_validation} ${item.nombre_validation > 1 ? I18n.t('VALIDATIONS') : I18n.t('VALIDATION')})`}
                            </Text>
                        </View>

                        <View style={{alignContent: 'flex-end', flex: 1, flexDirection: 'row'}}>
                            <Icon name="map-marker"
                                  style={[styles.descriptionIcon], {color: Color.accentColor, marginTop: 5}}/>
                            <Text style={styles.time}>{item.country}</Text>

                            <Icon name="clock"
                                  style={[styles.descriptionIcon], {color: Color.accentColor, marginTop: 5}}/>
                            <Text style={styles.time}> {dateFormat}</Text>
                        </View>

                    </View>

                </View>
            </TouchableOpacity>
        )
    }

    rendeGetDemandsGroupResponse = () => {

        const {resultGetDemandsGroup, errorGetDemandsGroup} = this.props;

        if (errorGetDemandsGroup !== null) {
            if (typeof errorGetDemandsGroup.data !== 'undefined') {
                return (
                    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                        <Text style={Typography.body1}>{errorGetDemandsGroup.data.error}</Text>
                    </View>
                )
            } else {
                return (
                    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                        <Text style={Typography.body1}>{errorGetDemandsGroup}</Text>
                    </View>
                )
            }
        }

        if (resultGetDemandsGroup !== null) {
            if (resultGetDemandsGroup.response !== null) {
                return (
                    Array.isArray(resultGetDemandsGroup.response) && (resultGetDemandsGroup.response.length) > 0 ?
                        (<ScrollView style={{flex: 1}}>
                            {
                                resultGetDemandsGroup.response.map((item) => (
                                    this.renderDemandItem(item)
                                ))
                            }
                        </ScrollView>) :
                        (
                            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                                <Text style={Typography.body1}>{I18n.t('NO_DEMAND_CREATION_GROUP')}</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>
        )
    }

    printOptions() {
        return (<ActionButton buttonColor={accent}>
            <ActionButton.Item buttonColor={primary} title={I18n.t('CREATE_GROUP')}
                               onPress={() => {
                                   this.props.navigation.push(route.createGroupNanoCredit);
                               }}
            >
                <Icon name="account-multiple-plus" style={styles.actionButtonIcon}/>
            </ActionButton.Item>
            <ActionButton.Item buttonColor={purpleLight} title={I18n.t('JOIN_GROUP')}
                               onPress={() => {
                                   this.props.navigation.push(route.adhererGroupNanoCredit);
                               }}
            >
                <Icon name="account-multiple" style={styles.actionButtonIcon}/>
            </ActionButton.Item>
        </ActionButton>)
    }

    refreshData() {
        this.props.getNanoCreditDemandsAction(this.state.user.id);
    }

    render() {
        console.warn("POSITION", this.state.position);
        return (
            <Provider>
                <View style={{flex: 1}}
                >
                    <StatusBar
                        backgroundColor={theme.primaryDark}
                        barStyle="light-content"
                        translucent={false}
                    />

                    <Appbar.Header dark={true} style={{backgroundColor: theme.primary}}>
                        <Appbar.BackAction
                            onPress={() => {
                                this.props.navigation.pop()
                            }}
                        />
                        <Appbar.Content
                            title={I18n.t('MANAGE_GROUP')}
                            subtitle={this.state.position === 0 ? I18n.t('VALIDATION_DEMAND') : I18n.t('DELETE_DEMAND')}
                        />
                        <Appbar.Action icon="refresh" onPress={() => {
                            this.refreshData()
                        }}/>
                        {/* <Appbar.Action icon="more-vert" onPress={() => { this._openMenu(); this.renderSliding(); }} /> */}
                    </Appbar.Header>

                    {this.state.position === 0 ?
                        this.props.loadingGetDemandsGroup ?
                            this.renderLoader() :
                            this.rendeGetDemandsGroupResponse()
                        : null}
                    {this.state.position === 0 && this.printOptions()}
                </View>
            </Provider>
        );

    }
}

const mapStateToProps = state => ({
    loadingGetDemandsGroup: state.getDemandsGroupReducer.loading,
    resultGetDemandsGroup: state.getDemandsGroupReducer.result,
    errorGetDemandsGroup: state.getDemandsGroupReducer.error,
});

const mapDispatchToProps = dispatch => bindActionCreators({
    getNanoCreditDemandsAction: getNanoCreditDemandsAction,
    getNanoCreditDemandsReset: getNanoCreditDemandsReset
}, dispatch);

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

const styles = StyleSheet.create({
    slidingup: {
        position: "absolute",
        height: responsiveHeight(84),
        bottom: 0,
        backgroundColor: 'white',
        width: responsiveWidth(100),
        zIndex: 1000
    },
    root: {
        flex: 1,
    },
    container: {
        flex: 1,
        backgroundColor: 'white',
        justifyContent: 'center',
        alignItems: 'center',
    },
    emptylist: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    backgroundd_drawer: {
        backgroundColor: '#000',
    },
    listbackground: {},
    actionButtonIcon: {
        fontSize: 20,
        height: 22,
        color: 'white',
    },
    descriptionIcon: {
        fontSize: 10,
        height: 12,
        top: 10
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
    dateText: {
        marginTop: 20,
        marginLeft: responsiveWidth(13),
        marginBottom: 20,
        fontSize: 17,
    },
    titlecontent: {
        fontSize: 17,
        marginLeft: responsiveWidth(10),

        color: 'black'
    },
    title: {
        fontSize: 20,
        marginLeft: 20,
        marginTop: 20,
        color: 'black',
        fontWeight: 'bold'
    },
    content: {
        flex: 1,
        flexDirection: 'column',
        paddingTop: 10,

    },
    listStyle: {
        backgroundColor: 'white'
    },
    bottomSeparator: {
        width: responsiveWidth(100),
        height: 5,
        justifyContent: 'center',
        alignSelf: 'center',
        backgroundColor: '#EEE',
    },
    title: {
        color: '#000',
        paddingLeft: 10,
        fontSize: responsiveFontSize(2.2)
    },
    description: {
        fontSize: responsiveFontSize(1.8),
        color: '#4f5b62',
        paddingLeft: 10,

    },
    timeContent: {
        justifyContent: 'space-between',
        flex: 1,
        marginTop: 10,
        marginBottom: 5,
        flexDirection: 'row',
    },
    time: {
        fontWeight: 'bold',
        marginRight: 20,
        marginBottom: 10,
        color: theme.accent,
    },
    paymentItem: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        width: "100%",
        borderBottomColor: '#EEE',
        borderBottomWidth: 1
    },
    iconContent: {
        width: 40,
        marginRight: 5,
        alignItems: "center"
    }
});
