import isEqual from 'lodash/isEqual';
import isNil from 'lodash/isNil';
import React, {Component} from 'react';
import {
    ActivityIndicator,
    Alert,
    Platform,
    ProgressBarAndroid,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import I18n from 'react-native-i18n';
import {responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';
import {ProgressDialog} from 'react-native-simple-dialogs';
import {connect} from 'react-redux';
import omit from 'lodash/omit';
import {bindActionCreators} from 'redux';
import {Color} from '../../config/Color';
import {IlinkEmitter} from '../../utils/events';
import {readUser} from '../../webservice/AuthApi';
import {refundCreditDemandUserAction, refundCreditDemandUserReset} from '../../webservice/user/NanoCreditApi';
import {
    getNanoCreditUserHistoryInProgressAction,
    getNanoCreditUserHistoryInProgressReset,
} from "../../webservice/NanoCreditApi";
import {Typography} from "../../config/typography";
import {
    cutString,
    cutStringWithoutDot,
    displayTransactionType,
    nanoCreditHistoryLabel
} from "../../utils/UtilsFunction";
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import thousands from "thousands";
import * as Utils from "../../utils/DeviceUtils";
import Dialog from "react-native-dialog";

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


class RefundNanoCreditUser extends Component {

    constructor(props) {
        super(props);
        this.state = {
            password: null,
            idDemand: null,
            codeGroup: null,
            loading: false,
            user: null,
            triggerSubmitClick: false,
            isSubmitClick: false,
            isDataSubmit: false,
            isModalConfirmVisible: false,
            isGroupToModify: false,
            displayModalHistory: false,
            historyItemDetail: null,
            isDataHasLoaded: false,
            displayPasswordModal: false,
            wallet: this.props.navigation.state.params.wallet,

        };
        this.props.getNanoCreditUserHistoryInProgressReset();

    }

    static navigatorStyle = {
        navBarBackgroundColor: Color.primaryColor,
        statusBarColor: Color.primaryDarkColor,
        navBarTextColor: '#FFFFFF',
        navBarButtonColor: '#FFFFFF'

    };

    static navigationOptions = () => {
        return {
            drawerLabel: () => null,
            headerTitle: I18n.t('REFUND_NANO_CREDIT'),
            headerTintColor: 'white',
            headerStyle: {
                backgroundColor: Color.primaryColor,
                marginTop: 0,
                color: 'white'
            },
            headerTitleStyle: {
                color: "white"
            },
            title: I18n.t('REFUND_NANO_CREDIT')
        }
    };

    componentDidMount() {

        readUser().then((user) => {
            if (user) {
                if (user !== undefined) {
                    this.setState({user});
                    this.props.getNanoCreditUserHistoryInProgressAction(user.id);
                }
            }
        });

    }

    ckeckIfFieldIsOK(champ) {
        return (isNil(champ) || isEqual(champ.length, 0));
    }

    renderRefundNanoCreditResponse = () => {

        const {result, error} = this.props;

        if (error !== null) {
            if (typeof error.data !== 'undefined') {
                Alert.alert(
                    I18n.t("ERROR_LABLE"),
                    error.data.error,
                    [
                        {
                            text: I18n.t("OK"), onPress: () => {
                                this.props.refundCreditDemandUserReset();
                            }
                        }
                    ],
                    {cancelable: false}
                )
            }
        }

        if (result !== null) {
            if (result.response !== null) {
                Alert.alert(
                    I18n.t("REFUND_DONE"),
                    result.response,
                    [
                        {
                            text: I18n.t("OK"), onPress: () => {
                                this.props.refundCreditDemandUserReset();
                                IlinkEmitter.emit("refreshWallet");
                                IlinkEmitter.emit("updateNanoCreditAccount");
                                this.props.navigation.pop();
                            }
                        }

                    ],
                    {cancelable: false}
                )
            }
        }
    }

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

    ckeckIfFieldIsOK(champ) {
        return (isNil(champ) || isEqual(champ.length, 0));
    }

    onSubmitRefundNanoCredit = () => {
        const {idDemand, password} = this.state;

        if (this.ckeckIfFieldIsOK(idDemand))
            this.idDemandAnim.shake(800);
        else if (this.ckeckIfFieldIsOK(password))
            this.passwordAnim.shake(800);
        else {

            this.props.refundCreditDemandUserAction({
                id_user: this.state.user.id,
                id_demande: this.state.idDemand,
                password: this.state.password
            }, 0);
        }
        this.setState({
            isDataSubmit: true
        });
    }


    renderLoader = () => {
        return (
            <ProgressDialog
                visible={this.props.loading || this.props.loadingGetCommission}
                title={I18n.t('LOADING')}
                message={I18n.t('LOADING_INFO')}
            />
        )
    }

    renderModalHistoryDetail = () => {
        return (

            <Dialog.Container useNativeDriver={true} visible={this.state.displayModalHistory}>

                <Dialog.Title>{I18n.t('DEMAND_DETAIL')}</Dialog.Title>
                {
                    <ScrollView persistentScrollbar={true}>
                        <View style={[styles.blockView, {borderBottomColor: Color.borderColor}]}>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>Type</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{I18n.t(displayTransactionType(this.state.historyItemDetail.type_historique))}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('ID_DEMAND')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.id_demande}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('STATUS')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.etat}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('DEMAND_DURATION_IN_MONTH')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.duree_mois}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text tyle={[Typography.body2]}>{I18n.t('AMOUNT')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.montant + ' ' + this.state.wallet.currency_code}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text tyle={[Typography.body2]}>{I18n.t('AMOUNT_REFUND')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.montant_rembourse + ' ' + this.state.wallet.currency_code}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text tyle={[Typography.body2]}>{I18n.t('AMOUNT_PARTIALLY_REFUND')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.partiellement_rembourse + ' ' + this.state.wallet.currency_code}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text tyle={[Typography.body2]}>{I18n.t('TAXES')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.taxe + ' ' + this.state.wallet.currency_code}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text tyle={[Typography.body2]}>{I18n.t('INTERET')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.interet + ' ' + this.state.wallet.currency_code}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text tyle={[Typography.body2]}>{I18n.t('WITHDRAWAL_IN_CASH')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.retrait_cash == 1 ? I18n.t('YES') : I18n.t('NO')}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('CREATION_DATE')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.date_creation}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text tyle={[Typography.body2]}>{I18n.t('VALIDATION_DATE')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.date_validation}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text tyle={[Typography.body2]}>{I18n.t('DATE_REMBOURSEMENT_PREVU')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.date_remboursement_prevu}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text tyle={[Typography.body2]}>{I18n.t('DATE_REMBOURSEMENT')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{this.state.historyItemDetail.date_remboursement}</Text>
                                </View>
                            </View>
                        </View>
                    </ScrollView>

                }
                <Dialog.Button bold={true} label={I18n.t('CANCEL_LABEL')} onPress={() => {
                    this.setState({
                        displayModalHistory: !this.state.displayModalHistory,
                    });

                }}/>

                <Dialog.Button bold={true} label={I18n.t('SUBMIT_LABEL')} onPress={() => {

                    this.setState({
                        displayPasswordModal: !this.state.displayPasswordModal,
                    });

                }}/>

            </Dialog.Container>

        );
    }

    renderPasswordDialog = () => {
        return (
            <Dialog.Container useNativeDriver={true} visible={this.state.displayPasswordModal}>

                <Dialog.Title>{I18n.t('PASSWORD')}</Dialog.Title>

                <Dialog.Input placeholder={I18n.t('PLEASE_ENTER_THE_PASSWORD')}
                              style={{borderBottomWidth: 1, borderBottomColor: Color.borderColor}}
                              showSoftInputOnFocus={true}
                              onChangeText={(password) => {
                                  this.setState({password})
                              }}
                              secureTextEntry={true}
                              value={this.state.password}
                              onSubmitEditing={() => {
                                  this.setState({
                                      displayPasswordModal: false,
                                      displayModalHistory: false,
                                      isDataSubmit: true
                                  });
                                  this.props.refundCreditDemandUserAction({
                                      id_user: this.state.user.id,
                                      id_demande: this.state.historyItemDetail.id_demande,
                                      password: this.state.password
                                  });
                              }}/>

                <Dialog.Button label={I18n.t('CANCEL_LABEL')} onPress={() => {
                    this.setState({displayPasswordModal: !this.state.displayPasswordModal});
                }}/>
                <Dialog.Button label={I18n.t('SUBMIT_LABEL')} onPress={() => {
                    this.setState({
                        displayPasswordModal: false,
                        displayModalHistory: false,
                        isDataSubmit: true
                    });
                    this.props.refundCreditDemandUserAction({
                        id_user: this.state.user.id,
                        id_demande: this.state.historyItemDetail.id_demande,
                        password: this.state.password
                    });
                }}/>
            </Dialog.Container>
        );
    }

    renderNanoCreditItem = (item, index) => {

        return (
            <TouchableOpacity onPress={() => {
                this.setState({displayModalHistory: true, historyItemDetail: item})
            }} style={[styles.contentService, {borderBottomColor: Color.primaryColor}]}>
                {
                    Object.keys(omit(item, ['id', 'id_demande', 'type_caution', 'agent', 'retrait_cash', 'date_remboursement_prevu', 'taxe', 'date_validation', 'duree_mois', 'interet', 'montant_rembourse', 'partiellement_rembourse',])).map((element, i) => (
                        <View style={{alignItems: 'center'}} key={i}>

                            <Text style={[Typography.overline, Color.grayColor], {marginTop: 4}}>
                                {
                                    isEqual(element, 'montant') ?
                                        `  ${item[element].length > 8 ? cutString(thousands(item[element], ' '), 6) : thousands(item[element], ' ')} ${this.state.wallet.currency_code}`
                                        : isEqual(element, 'date_creation') ?
                                        cutStringWithoutDot(item[element], 16)
                                        : item[element]
                                }
                            </Text>
                        </View>
                    ))
                }
            </TouchableOpacity>
        );
    }

    renderNanoCreditList = () => {
        const {errorNanoCreditHistory, resultNanoCreditHistory} = this.props;
        if (errorNanoCreditHistory !== null) {
            if (typeof errorNanoCreditHistory.data !== 'undefined') {
                return (
                    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                        <Text style={Typography.body1}>{errorNanoCreditHistory.data.error}</Text>
                    </View>
                )
            } else {
                return (
                    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                        <Text style={Typography.body1}>{errorNanoCreditHistory}</Text>
                    </View>
                )
            }
        }


        if (resultNanoCreditHistory !== null) {
            if (resultNanoCreditHistory.response !== null) {
                return (
                    Array.isArray(resultNanoCreditHistory.response) && (resultNanoCreditHistory.response.length) > 0 ?
                        (
                            <>
                                <View style={[styles.contentService, {borderBottomColor: Color.primaryColor}]}>
                                    {
                                        nanoCreditHistoryLabel().map((item, index) => (
                                            <View style={{alignItems: 'center'}} key={index}>
                                                <Icon name={item.icon} size={24} color={Color.primaryColor}/>
                                                <Text style={[Typography.overline, Color.grayColor], {marginTop: 4}}>
                                                    {I18n.t(item.label)}
                                                </Text>
                                            </View>
                                        ))
                                    }
                                </View>
                                {
                                    resultNanoCreditHistory.response.map((item, index) => (
                                        this.renderNanoCreditItem(item, index)
                                    ))
                                }
                            </>
                        ) :
                        (
                            <View style={{flex: 1, justifyContent: 'center', alignItems: 'flex-start'}}>
                                <Text style={Typography.body1}>{I18n.t('NO_NANO_CREDIT')}</Text>
                            </View>
                        )
                )
            }
        }
    }

    renderNanoCreditHistory = () => {
        return (
            <View style={{backgroundColor: Color.containerBackgroundColor, flex: 1}}>

                {
                    this.props.loadingNanoCreditHistory ?
                        (
                            <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>
                        ) : this.renderNanoCreditList()

                }
            </View>
        );
    }

    render() {
        return (
            <>
                {(this.props.loading || this.props.loadingGetCommission) && this.renderLoader()}
                {this.state.isDataSubmit && this.renderRefundNanoCreditResponse()}
                {this.state.displayModalHistory && this.renderModalHistoryDetail()}
                {this.state.displayPasswordModal && this.renderPasswordDialog()}
                <ScrollView style={styles.container}>

                    <View style={[styles.checkDefault, {borderBottomColor: Color.borderColor}]}>
                        <Text
                            style={[Typography.title3, Typography.semibold]}>
                            {I18n.t('NANO_CREDIT_LIST')}
                        </Text>
                    </View>

                    {
                        this.renderNanoCreditHistory()
                    }
                    {/*                    <Text style={styles.subbigtitle}>{I18n.t('DEMAND_INFO')}</Text>

                    <Animatable.View ref={(comp) => {
                        this.idDemandAnim = comp
                    }}>
                        <Fumi iconClass={FontAwesomeIcon} iconName={'id-card'}
                              label={I18n.t('ID_DEMAND')}
                              iconColor={'#f95a25'}
                              iconSize={20}
                              value={this.state.idDemand}
                              onChangeText={(idDemand) => {

                                  this.setState({idDemand})
                              }}
                              style={styles.input}
                        >
                        </Fumi>
                    </Animatable.View>


                    <Animatable.View ref={(comp) => {
                        this.passwordAnim = comp
                    }}>
                        <Fumi iconClass={FontAwesomeIcon} iconName={'lock'}
                              label={I18n.t('PASSWORD')}
                              iconColor={'#f95a25'}
                              iconSize={20}
                              secureTextEntry={true}
                              value={this.state.password}
                              onChangeText={(password) => {
                                  this.setState({password})
                              }}
                              style={styles.input}
                        >
                        </Fumi>
                    </Animatable.View>

                    <Button style={styles.btnvalide}
                            textStyle={styles.textbtnvalide}
                            onPress={() => {
                                this.onSubmitRefundNanoCredit();
                            }}>
                        {this.state.isGroupToModify ? I18n.t('MODIFY') : I18n.t('SUBMIT_LABEL')}</Button>*/}
                </ScrollView>
            </>
        )
    }
}

const maptStateToProps = state => ({

    loading: state.refundCreditDemandReducer.loading,
    result: state.refundCreditDemandReducer.result,
    error: state.refundCreditDemandReducer.error,

    loadingNanoCreditHistory: state.getNanoCreditUserHistoryInProgressReducer.loading,
    resultNanoCreditHistory: state.getNanoCreditUserHistoryInProgressReducer.result,
    errorNanoCreditHistory: state.getNanoCreditUserHistoryInProgressReducer.error,
});

const mapDispatchToProps = dispatch => bindActionCreators({

    refundCreditDemandUserAction,
    refundCreditDemandUserReset,
    getNanoCreditUserHistoryInProgressAction,
    getNanoCreditUserHistoryInProgressReset

}, dispatch);

export default connect(maptStateToProps, mapDispatchToProps)(RefundNanoCreditUser);

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Color.containerBackgroundColor,
        paddingHorizontal: 20
    },
    textbtnvalide: {
        color: 'white',
        fontWeight: 'bold'
    },
    bigtitle: {
        color: 'white',
        fontSize: 20,
        flex: 1,
        fontWeight: 'bold',
        textAlign: 'center',
        margin: 20,
    },
    blockView: {
        paddingVertical: 10,
        borderBottomWidth: 1
    },
    subbigtitle: {
        color: 'white',
        fontSize: 17,
        textAlign: 'center',
        margin: 5,
    },
    btnvalide: {
        marginTop: 20,
        marginLeft: 20,
        marginRight: 20,
        borderColor: 'transparent',
        backgroundColor: Color.accentLightColor,
        height: 52
    },
    btnSubmit: {
        marginTop: 20,
        borderColor: 'transparent',
        backgroundColor: Color.accentLightColor,
        height: 52,
        width: "30%",
        marginLeft: 20,
        marginRight: 20,
    },
    input: {
        height: 60,
        marginTop: responsiveHeight(2),
        marginLeft: responsiveWidth(5),
        marginRight: responsiveWidth(5),
        borderRadius: 5,
    },
    circlePoint: {
        width: 50,
        height: 50,
        borderRadius: 25,
        marginRight: 5,
        alignItems: 'center',
        justifyContent: 'center',
    },
    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(65),
        paddingHorizontal: 10,
        justifyContent: 'space-between',
        alignItems: 'flex-start',
        flex: 1,
    },
    contentTitle: {
        paddingTop: 12,
    },
    contentService: {
        paddingVertical: 10,
        borderBottomWidth: 0.5,
        flexDirection: 'row',
        flexWrap: 'wrap',
        justifyContent: 'space-between',
    },
    containField: {
        padding: 10,
        marginBottom: 20,
        borderWidth: 0.5,
        shadowOffset: {width: 1.5, height: 1.5},
        shadowOpacity: 1.0,
        elevation: 5,
        flexDirection: "row",
        height: 140,
        borderRadius: 10
    },
    paymentItem: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        borderBottomWidth: 1,
        paddingVertical: 5,
        width: responsiveWidth(100),
        marginBottom: 15
    },
    iconContent: {
        width: 60,
        marginRight: 10,
        alignItems: "center"
    },
    contentLeftItem: {
        flex: 1,
        paddingTop: 40,
        paddingLeft: 10,
        paddingRight: 10,
        alignItems: "center"
    },
});