import React from 'react';
import { View, Text, TextInput, StyleSheet, Button, ScrollView, Alert, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import Axios from 'axios';
import ActionType from '../redux/globalActionType';
import Spinner from 'react-native-loading-spinner-overlay';
import session from '../function/session';
import i18n from 'i18n-js';

class CardActivation extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            session_id: "",
            mobile_phone: "",
            card_number: "",
            card_nums: this.props.route.params.cardNumber,
            token: "",
            timer: 80,
            onclickToken: false,
            onclick: false,
            spinner: false,
            caretHidden: true,

        }
    }

    componentDidMount() {
        console.log("INI CARD NUMBER" + this.props.card_number)
        console.log("INI BASE_URL " + this.props.BASE_URL)
    }

    componentDidUpdate(prevProps) {
        if (this.state.timer === 0) {
            clearInterval(this.interval);
        }

    }

    componentWillUnmount() {
        clearInterval(this.interval);
    }


    _getProfile() {
        let params = {
            session_id: this.props.session_id,
            lat: this.state.my_lat,
            long: this.state.my_long,
            closest_outlet: 1

        }

        Axios.post(this.props.BASE_URL + 'crm/v2/member/get_profile', params).then(res => {
            console.log("INI DATANYA : " + JSON.stringify(res))
            const dataCard = res.data
            console.log(dataCard)
            let email = dataCard.email
            let point = dataCard.kaspro_point
            let balance = dataCard.kaspro_balance
            let img_card = dataCard.card_series_image
            let member_since = dataCard.member_since
            let expire = dataCard.expire_date
            let premium = dataCard.kaspro_is_premium
            let kaspro = dataCard.kaspro_account_number
            let full_name = dataCard.name
            let old_balance_claimed = dataCard.old_balance_claimed
            let old_balance = dataCard.old_balance
            let is_expired = dataCard.is_expired
            let account_number = dataCard.card_number

            this.setState({
                email: email,
                points: point,
                img_card: img_card,
                member_since: member_since,
                balance: balance,
                account_number: account_number,
                img_card: img_card,
                expire_date: expire,
                premium: premium,
                full_name: full_name,
                indicator: false,
                old_balance_claimed: old_balance_claimed,
                old_balance: old_balance,
                is_expired: is_expired,
            })

        }).catch(error => {
            // const { navigation } = this.props
            // let response = error.response.data
            // session(response, navigation)
            let response = error.response.data
            // Alert.alert('',response.msg);
            Toast.show(response.msg)
        })
    }

    handleToken() {
        this.setState({
            spinner: true,
        })
        if (this.state.mobile_phone == '') {
            Alert.alert('', 'Masukan No telp ');
        } else {
            let params = {
                session_id: this.props.session_id,
                mobile_phone: this.state.mobile_phone
            }
            Axios.post(this.props.BASE_URL + 'crm/v2/get_token', params).then(res => {
                this.setState({
                    onclick: true
                })
                Alert.alert('Kami telah mengirimkan sms otp ke nomor anda!');
                this.interval = setInterval(
                    () => this.setState((prevState) => ({ timer: prevState.timer - 1 })),
                    1000
                );
                this.setState({
                    onclick: true,
                    spinner:false
                })
                
            }).catch(error => {
                let response = error.response.data;
                // const { navigation } = this.props
                // session(response, navigation)
                Alert.alert('', response.msg);
            })
        }

    }

    ResendToken() {
        this.setState({
            spinner: true,
        })
        let params = {
            session_id: this.props.session_id,
            mobile_phone: this.state.mobile_phone
        }
        Axios.post(this.props.BASE_URL + 'crm/v2/resend_token', params).then(res => {
            this.setState({
                spinner: false,
            })

            Alert.alert('Kami telah kembali mengirimkan sms otp ke nomor anda!');
            this.setState({
                timer: 80
            })
            this.interval = setInterval(
                () => this.setState((prevState) => ({ timer: prevState.timer - 1 })),
                1000
            );
        }).catch(error => {
            this.setState({
                spinner: false,
            })
            let response = error.response.data;
            Alert.alert('', response.msg);
        })
    }

    handlecardNumberNotnull() {
        let params = {
            session_id: this.props.session_id,
            mobile_phone: this.state.mobile_phone,
            card_number: this.state.card_number,
            token: this.state.token
        }

        console.log("INI PARAMS " + JSON.stringify(params))

        Axios.post(this.props.BASE_URL + 'crm/v2/card/activate', params).then(res => {
            let setCardNumberProps = {
                card_number: ""
            }
            this.props.setCardNumber(setCardNumberProps)
            Alert.alert(
                "",
                "Kartu anda berhasil di aktifkan",
                [
                    {
                        text: "OK", onPress: () => {
                            this.setState({ spinner: false })
                            this.props.navigation.reset({
                                index: 0,
                                routes: [{ name: 'Home' }],
                            })
                        }
                    }
                ],
            );
        }).catch(error => {
            let response = error.response.data;
            Alert.alert(
                '',
                response.msg,
                [
                    { text: "OK", onPress: () => this.setState({ spinner: false }) }
                ],
            );
        })
    }

    handlecardNumbernull() {
        let params = {
            session_id: this.props.session_id,
            mobile_phone: this.state.mobile_phone,
            card_number: this.state.card_nums,
            token: this.state.token
        }

        console.log("INI STATENYA " + this.state.card_nums)

        console.log("INI PARAMS " + JSON.stringify(params))

        Axios.post(this.props.BASE_URL + 'crm/v2/card/activate', params).then(res => {
            let setCardNumberProps = {
                card_number: ""
            }
            this.props.setCardNumber(setCardNumberProps)
            Alert.alert(
                "",
                "Kartu anda berhasil di aktifkan",
                [
                    {
                        text: "OK", onPress: () => {
                            this.setState({ spinner: false })
                            this.props.navigation.reset({
                                index: 0,
                                routes: [{ name: 'Home' }],
                            })
                        }
                    }
                ],
            );
        }).catch(error => {
            let response = error.response.data;
            Alert.alert(
                '',
                response.msg,
                [
                    { text: "OK", onPress: () => this.setState({ spinner: false }) }
                ],
            );
        })
    }

    handleActivate() {

        this.setState({
            spinner: true,
        })

        if (this.props.card_number == '') {
            this.handlecardNumberNotnull()
        } else {
            this.handlecardNumbernull()
        }

    }

    render() {
        return (
            <ScrollView style={styles.container}>
                <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                />

                <View style={styles.form}>
                    <View style={styles.field_phone}>
                        <View style={{ flex: 1, margin: 10 }}>
                            <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 19, textAlign: 'center', marginBottom: 5 }}>{i18n.t('mobilePhone')}</Text>
                            <TextInput
                                style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 5, borderRadius: 10, textAlign: 'center', fontFamily: 'Gotham-Black', color: 'grey', fontSize: 16 }}
                                onChangeText={mobile_phone => this.setState({ mobile_phone })}
                                keyboardType='numeric'
                                value={this.state.mobile_phone}
                                caretHidden={this.state.caretHidden}
                                onFocus={() => this.setState({ caretHidden: false })}

                            />
                        </View>
                        <View style={styles.button}>
                            {this.state.onclick == true ? (null) : (
                                <TouchableOpacity style={{ top: 25 }} onPress={() => this.handleToken()}>
                                    <View style={{ height: 40, borderRadius: 10, backgroundColor: '#CFB368', justifyContent: 'center' }}>
                                        <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 20, textAlign: 'center', margin: 10 }}>Token</Text>
                                    </View>
                                </TouchableOpacity>
                            )}
                        </View>
                    </View>
                    {
                        this.state.onclick === true ? (<Text style={{ textAlign: 'center', fontFamily: 'Gotham-Black',color:'red' }}> 0:{this.state.timer} </Text>) : (
                            null
                        )

                        
                    }

                    {
                        this.state.timer === 0 ? (
                            <TouchableOpacity onPress={() => this.ResendToken()}>
                                <View style={{ height: 40, borderRadius: 10, backgroundColor: '#CFB368', margin: 20, justifyContent: 'center' }}>
                                    <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 20, textAlign: 'center' }}>{i18n.t('resend')}</Text>
                                </View>
                            </TouchableOpacity>
                        ) : (null)}

                    <View style={styles.field_email}>
                        <View style={{ flex: 1, margin: 10 }}>
                            <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 19, textAlign: 'center', marginBottom: 5 }}>{i18n.t('cardNumber')}</Text>
                            {this.state.card_nums == "" ? (
                                <TextInput
                                    style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 5, borderRadius: 10, textAlign: 'center', fontFamily: 'Gotham-Black', color: 'grey', fontSize: 16 }}
                                    onChangeText={card_number => this.setState({ card_number })}
                                    keyboardType='numeric'
                                    caretHidden={this.state.caretHidden}
                                    onFocus={() => this.setState({ caretHidden: false })}
                                />
                            ) : (
                                    <TextInput
                                        style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 5, borderRadius: 10, textAlign: 'center', fontFamily: 'Gotham-Black', color: 'grey', fontSize: 16 }}
                                        onChangeText={card_nums => this.setState({ card_nums })}
                                        value={this.props.card_number}
                                        editable={false}
                                        caretHidden={this.state.caretHidden}
                                        defaultValue={this.props.card_nums}
                                        onFocus={() => this.setState({ caretHidden: false })}
                                    />
                                )}
                        </View>
                    </View>
                    <View style={styles.field_email}>
                        <View style={{ flex: 1, margin: 10 }}>
                            <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 19, textAlign: 'center', marginBottom: 5 }}>Token</Text>
                            <TextInput
                                style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 5, borderRadius: 10, textAlign: 'center', fontFamily: 'Gotham-Black', color: 'grey', fontSize: 16 }}
                                onChangeText={token => this.setState({ token })}
                                value={this.state.token}
                                keyboardType='numeric'
                                caretHidden={this.state.caretHidden}
                                onFocus={() => this.setState({ caretHidden: false })}
                            />
                        </View>
                    </View>
                    <View style={styles.button}>
                        <TouchableOpacity onPress={() => this.handleActivate()}>
                            <View style={{ height: 40, borderRadius: 10, backgroundColor: '#CFB368', margin: 20, justifyContent: 'center' }}>
                                <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 20, textAlign: 'center' }}>{i18n.t('activate')}</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>
            </ScrollView>
        )
    }
}

const styles = StyleSheet.create({

    container: {
        flex: 1,
        backgroundColor: '#ffff'
    },

    header: {
        flex: 0.5,
        margin: 10,
    },

    form: {
        flex: 3,
        margin: 5,
        marginTop: 50,
    },

    field_email: {
        flexDirection: 'row'
    },

    field_phone: {
        flexDirection: 'row'
    },

    button: {
        height: 50,
        margin: 10,

    }
})

const mapStateToProps = (state) => {
    return {
        session_id: state.session_id,
        set_card: state.set_card,
        card_number: state.card_number,
        BASE_URL: state.BASE_URL,
    }
}

const mapDispatchToProps = (dispacth) => {
    return {

        setCardNumber: (setCardNumberProps) => dispacth({

            type: ActionType.SET_ACCOUNT_NUMBER,
            data: {
                card_number: setCardNumberProps.card_number,
            }
        }),
    }
}


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