import React from 'react';
import { View, Text, StyleSheet, Button, Alert, TouchableOpacity, ActivityIndicator } from 'react-native';
import { connect } from 'react-redux';
import Axios from 'axios';
import MyStatusBar from './MyStatusBar';
import i18n from 'i18n-js';
import Toast from 'react-native-tiny-toast';
import Spinner from 'react-native-loading-spinner-overlay';
import moment from 'moment'
import NumberFormat from 'react-number-format';


class Renewal extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            current_balance: "",
            expired: "",
            card_number: "",
            renew_until: "",
            indicator: true,
            spinner: false,
            hide_renew_button: false,
            renewal_cost: 0
        }
    }

    componentDidMount() {
        this._getProfile();
        // console.log(this.props.BASE_URL)
    }

    _handleRenewal() {
        Alert.alert(
            i18n.t('alertRenewalTitle'),
            i18n.t('alertRenewalContent'),
            [
                {
                    text: i18n.t('alertno'),
                    onPress: () => console.log('Cancel Renewal'),
                    style: 'cancel',
                },
                {
                    text: i18n.t('alertyes'), onPress: () => this._renewal()
                },
            ],
            { cancelable: false },
        )
    }

    _renewal() {
        this.setState({ spinner: true })
        let params = {
            session_id: this.props.session_id
        }
        // console.log(params);
        Axios.post(this.props.BASE_URL + 'crm/v2/card/renewal', params).then(res => {
            // console.log('ini res ' + JSON.stringify(res.data))
            this.setState({spinner: false})
            this._getProfile();
            Toast.show(i18n.t('successRenewal'))
            this.props.navigation.navigate('Home', { screen: 'ACCOUNT' });
        }).catch(error => {
            let msg = '';
            try {
                let response = error.response.data;
                msg = response.msg;
            } catch (err) {
                msg = 'Error Connection';
            } 
            Alert.alert(
                '',
                msg,
                [
                    {
                        text: 'OK', onPress: () => this.setState({
                            spinner: false,
                        })
                    }
                ]
            );
        })
    }

    _getProfile() {
        let params = {
            session_id: this.props.session_id
        }

        Axios.post(this.props.BASE_URL + 'crm/v2/member/get_profile', params).then(res => {
            const dataCard = res.data

            let balance = dataCard.kaspro_balance
            let expired = dataCard.expire_date
            let renew = dataCard.renew_until
            let renewal_cost = dataCard.renewal_cost

            let balance_replace = balance.replace(',','')

            this.setState({
                renewal_cost : renewal_cost
            })


            // cek apakah saldo kurang dari renewal_cost
            if (balance_replace < this.state.renewal_cost) {
                //kalau saldo sama kurang dari renewal cost disable renew button = true  
                this.setState({
                    current_balance: balance,
                    expired: expired,
                    renew_until: renew,
                    indicator: false,
                    hide_renew_button: true
                })

            } else {
                // kalau tidak hide renew button = false  
                this.setState({
                    current_balance: balance,
                    expired: expired,
                    renew_until: renew,
                    indicator: false,
                    hide_renew_button: false
                })
            }
        }).catch(error => {
            let msg = '';
            try {
                let response = error.response.data;
                msg = response.msg;
            } catch (err) {
                msg = 'Error Connection';
            } 
            Alert.alert(
                '',
                msg,
                [
                    {
                        text: 'OK', onPress: () => this.setState({
                            spinner: false,
                        })
                    }
                ]
            );
        })
    }

    render() {
        return (
            <View style={styles.container}>
                <MyStatusBar />
                {/* <View style={styles.header}> */}
                {/* <Text style={{ textAlign: 'center', margin: 20, fontSize: 25, alignSelf: 'center' }}>Renewal</Text> */}
                {/* </View> */}
                <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                />
                {
                    this.state.indicator ? (<ActivityIndicator style={{ top: 20, justifyContent: "center" }} size="large" color="#c9af6d" />) : (
                        <View style={styles.body}>
                            <View style={styles.cont_curent_balance}>
                                <View style={styles.current_balance}>
                                    <Text style={{ textAlign: 'center', fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368' }}>{i18n.t('currentbalance')}</Text>
                                </View>
                                <View style={styles.value_current_balance}>
                                    <Text style={{ textAlign: 'center', fontSize: 12, fontFamily: 'Gotham-Black', color: 'gray' }}>IDR {this.state.current_balance}</Text>
                                </View>
                            </View>
                            <View style={styles.cont_curent_balance}>
                                <View style={styles.current_balance}>
                                    <Text style={{ textAlign: 'center', fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368' }}>{i18n.t('renewalfees')}</Text>
                                </View>
                                <View style={styles.value_current_balance}>
                                    <NumberFormat decimalScale={0} value={this.state.renewal_cost} renderText={value => <Text style={{ textAlign: 'center', fontSize: 12, fontFamily: 'Gotham-Black', color: 'gray' }}>IDR {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                                </View>
                            </View>
                            <View style={styles.cont_curent_balance}>
                                <View style={styles.current_balance}>
                                    <Text style={{ textAlign: 'center', fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368' }}>{i18n.t('expired')}</Text>
                                </View>
                                <View style={styles.value_current_balance}>
                                    <Text style={{ textAlign: 'center', fontSize: 12, fontFamily: 'Gotham-Black', color: 'gray' }}>{this.state.expired}</Text>
                                </View>
                            </View>

                            <View style={styles.cont_curent_balance}>
                                <View style={styles.current_balance}>
                                    <Text style={{ textAlign: 'center', fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368' }}>{i18n.t('renewuntil')}</Text>
                                </View>
                                <View style={styles.value_current_balance}>
                                    <Text style={{ textAlign: 'center', fontSize: 12, fontFamily: 'Gotham-Black', color: 'gray' }}>{this.state.renew_until}</Text>
                                </View>
                            </View>  

                            {/* cek tombol berdasarkan state renew_button */}
                            {this.state.hide_renew_button == true ? 
                                <View style={{marginTop: 30}} >
                                    <Text style={{ color: 'red', fontSize: 16, textAlign: 'center', fontFamily: 'Gotham-Black' }}>{i18n.t('renewal_notEnoughBalance')}</Text>
                                </View>
                            : <TouchableOpacity onPress={() => this._handleRenewal()}>
                                <View style={styles.button}>
                                    <Text style={{ color: 'white', fontSize: 16, textAlign: 'center', fontFamily: 'Gotham-Black' }}>{i18n.t('renew')}</Text>
                                </View>
                            </TouchableOpacity>
                            }
                        </View>
                    )
                }
            </View>
        )
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white',
    },
    header: {
        flex: 0.1,
    },
    body: {
        flex: 0.9,
        marginTop: 12
    },
    cont_curent_balance: {
        flex: 0.2
    },
    current_balance: {
        flex: 1,
        // backgroundColor:'cyan',
        justifyContent: 'center',
    },
    value_current_balance: {
        flex: 1,
        marginHorizontal: 30,
        paddingHorizontal: 10,
        paddingVertical: 5,
        justifyContent: 'center',
        borderWidth: 1,
        borderColor: 'gray',
        borderRadius: 10,
        // backgroundColor:'maroon'
    },
    button: {
        height: 40,
        borderRadius: 10,
        backgroundColor: '#CFB368',
        justifyContent: 'center',
        margin: 30,
        padding: 5,
        bottom: 5,
    },
})

const mapStateToProps = (state) => {
    return {
        session_id: state.session_id,
        language: state.language,
        BASE_URL: state.BASE_URL
    }
}
export default connect(mapStateToProps)(Renewal);
