import Button from 'apsl-react-native-button';
import isEqual from 'lodash/isEqual';
import isNil from 'lodash/isNil';
import React, {Component} from 'react';
import {Alert, ScrollView, StyleSheet, Text, View} from 'react-native';
import * as Animatable from 'react-native-animatable';
import Dialog from "react-native-dialog";
import I18n from 'react-native-i18n';
import {store} from "../../redux/store";
import {Dropdown} from 'react-native-material-dropdown-v2';
import {responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';
import {ProgressDialog} from 'react-native-simple-dialogs';
import {Fumi} from 'react-native-textinput-effects';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {Color} from '../../config/Color';
import {Typography} from '../../config/typography';
import {IlinkEmitter} from '../../utils/events';
import {
    cautionCreditDemandAgentAction,
    cautionCreditDemandAgentReset,
    getNanoCreditDemandDetailAction,
    getNanoCreditDemandDetailReset
} from '../../webservice/agent/NanoCreditAgentApi';
import {readUser} from '../../webservice/AuthApi';
import {withdrawalMode} from '../../utils/UtilsFunction';
import thousands from 'thousands';

const moment = require('moment');

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


class CautionNanoCreditAgent extends Component {


    constructor(props) {
        super(props);
        this.state = {
            password: null,
            idDemand: null,
            codeGroup: null,
            loading: false,
            user: null,
            triggerSubmitClick: false,
            isSubmitClick: false,
            isDataSubmit: false,
            withdrawalInCashType: withdrawalMode(),
            withdrawalInCashTypeName: withdrawalMode()[0].name,
            isModalConfirmVisible: false,
            isGroupToModify: false,
            withdrawalInCash: true,
            wallet: store.getState().walletDetailReducer.result.response
        };
        console.log("Wallet", this.state.wallet);

        this.props.getNanoCreditDemandDetailReset();
        this.props.cautionCreditDemandAgentReset();

    }

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

    };

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

    componentDidMount() {

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

    }


    componentWillReceiveProps(nextProps) {

        if (nextProps.resultGetNanoCreditDemandDetail != null) {

            if (typeof nextProps.resultGetNanoCreditDemandDetail.response !== 'undefined') {

                if (!nextProps.loadingGetNanoCreditDemandDetail)
                    this.setState({
                        isModalConfirmVisible: true
                    });
            }
        }
    }

    modalConfirmTransaction = (data) => {
        const idDemand = data.response.id_demande;
        const montant = data.response.montant;
        const duree = data.response.duree_mois;
        const etat = data.response.etat;
        const taxe = data.response.taxe;
        const interet = data.response.interet;
        const dateDemand = data.response.date_demande;
        const dateRemboursementPrevu = data.response.date_remboursement_prevu;
        const dateRemboursement = data.response.date_remboursement;
        const retraitCash = data.response.retrait_cash;
        const dateCreation = data.response.date_creation;

        return (

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

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

                <View>

                    <View style={[styles.blockView, {borderBottomColor: Color.borderColor}]}>
                        <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]}>{idDemand}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('AMOUNT')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{`${thousands(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('TAXES')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{`${thousands(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]}>{`${thousands(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_TYPE')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{retraitCash ? I18n.t('WITHDRAWAL_IN_CASH') : I18n.t('TRANSFER_IN_ACCOUNT')}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text tyle={[Typography.body2]}>{I18n.t('ETAT')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text style={[Typography.caption1, Color.grayColor]}>{etat}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text tyle={[Typography.body2]}>{I18n.t('DEMAND_DURATION_IN_MONTH')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text style={[Typography.caption1, Color.grayColor]}>{duree}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text tyle={[Typography.body2]}>{I18n.t('CREATION_DATE')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{moment(dateCreation).format('DD-MM-YYYY')}</Text>
                            </View>
                        </View>
                    </View>
                </View>

                <Dialog.Button bold={true} label={I18n.t('CANCEL_LABEL')} onPress={() => {
                    this.setState({
                        isModalConfirmVisible: false
                    });
                }}/>
                <Dialog.Button bold={true} label={I18n.t('SUBMIT_LABEL')} onPress={() => {
                    this.setState({
                        isModalConfirmVisible: false,
                        isDataSubmit: true
                    });
                    this.props.cautionCreditDemandAgentAction({
                        id_demande: this.state.idDemand,
                        id_wallet_agent: this.state.wallet.id,
                        retrait_cash: this.state.withdrawalInCash,
                        password: this.state.password
                    });
                    this.props.getNanoCreditDemandDetailReset();
                }}/>

            </Dialog.Container>

        );

    }

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

    renderRefundNanoCreditResponse = () => {

        const {result, error} = this.props;

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

        }

        if (result !== null) {
            if (result.response !== null) {
                Alert.alert(
                    I18n.t("CAUTIONNEMENT_DONE"),
                    result.response,
                    [
                        {
                            text: I18n.t("OK"), onPress: () => {
                                this.props.cautionCreditDemandAgentReset();
                                IlinkEmitter.emit("refreshWallet");
                                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));
    }

    onSubmitCautionnerNanoCredit = () => {
        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.getNanoCreditDemandDetailAction(this.state.idDemand);
        }
        this.setState({
            triggerSubmitClick: true
        });
    }

    renderGetNanoCreditDemandDetailResponse = () => {
        const {resultGetNanoCreditDemandDetail, errorGetNanoCreditDemandDetail} = this.props;

        if (errorGetNanoCreditDemandDetail !== null) {
            if (typeof errorGetNanoCreditDemandDetail.data !== 'undefined') {
                Alert.alert(
                    I18n.t('ERROR_LABEL'),
                    errorGetNanoCreditDemandDetail.data.error,
                    [
                        {
                            text: I18n.t("OK"), onPress: () => {
                                this.props.getNanoCreditDemandDetailReset();
                            }
                        }

                    ],
                    {cancelable: false}
                )
            } else {
                Alert.alert(
                    I18n.t('ERROR_LABEL'),
                    JSON.stringify(errorGetNanoCreditDemandDetail),
                    [
                        {
                            text: I18n.t("OK"), onPress: () => {
                                this.props.getNanoCreditDemandDetailAction();
                            }
                        }

                    ],
                    {cancelable: false}
                )
            }
        }
    }


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

    render() {
        const {resultGetNanoCreditDemandDetail} = this.props;

        return (
            <>
                {(this.props.loading || this.props.loadingGetNanoCreditDemandDetail) && this.renderLoader()}
                {this.state.isDataSubmit && this.renderRefundNanoCreditResponse()}
                {this.state.triggerSubmitClick && this.renderGetNanoCreditDemandDetailResponse()}
                {
                    (resultGetNanoCreditDemandDetail !== null) &&
                    (typeof resultGetNanoCreditDemandDetail.response !== 'undefined') &&
                    this.modalConfirmTransaction(resultGetNanoCreditDemandDetail)
                }
                <ScrollView style={styles.container}>

                    <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.typeRetraitAnim = comp
                    }}
                                     style={{
                                         width: responsiveWidth(90),
                                         height: 60,
                                         marginTop: 20,
                                         alignSelf: 'center',
                                         borderRadius: 10,
                                         paddingLeft: 20,
                                         paddingRight: 20,
                                         backgroundColor: 'white'
                                     }}>
                        <Dropdown
                            label={I18n.t('WITHDRAWAL_TYPE')}
                            data={this.state.withdrawalInCashType}
                            useNativeDriver={true}
                            value={I18n.t(this.state.withdrawalInCashTypeName)}
                            onChangeText={(value, index, data) => {
                                if (value === I18n.t('WITHDRAWAL_IN_CASH'))
                                    this.setState({
                                        withdrawalInCash: true,
                                        withdrawalInCashTypeName: 'WITHDRAWAL_IN_CASH'
                                    });
                                else
                                    this.setState({
                                        withdrawalInCash: false,
                                        withdrawalInCashTypeName: 'TRANSFER_IN_ACCOUNT'
                                    })
                            }}
                            valueExtractor={(value) => {
                                return I18n.t(value.name)
                            }}
                            labelExtractor={(value) => {
                                return I18n.t(value.name)
                            }}
                        />
                    </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.onSubmitCautionnerNanoCredit();
                            }}>
                        {this.state.isGroupToModify ? I18n.t('MODIFY') : I18n.t('SUBMIT_LABEL')}</Button>
                </ScrollView>
            </>
        )
    }
}

const maptStateToProps = state => ({

    loading: state.cautionCreditDemandAgentReducer.loading,
    result: state.cautionCreditDemandAgentReducer.result,
    error: state.cautionCreditDemandAgentReducer.error,

    loadingGetNanoCreditDemandDetail: state.getNanoCreditDemandDetailReducer.loading,
    resultGetNanoCreditDemandDetail: state.getNanoCreditDemandDetailReducer.result,
    errorGetNanoCreditDemandDetail: state.getNanoCreditDemandDetailReducer.error,
});

const mapDispatchToProps = dispatch => bindActionCreators({

    cautionCreditDemandAgentAction,
    cautionCreditDemandAgentReset,

    getNanoCreditDemandDetailAction,
    getNanoCreditDemandDetailReset

}, dispatch);

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

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Color.primaryDarkColor,
    },
    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,
    }
});
