import * as React from 'react';
import { Button, View, Text, StyleSheet, TextInput, Alert, Image } from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
import Axios from 'axios';
import { connect } from 'react-redux';
import ActionType from '../redux/globalActionType';
import { BASE_URL_LOGIN } from '../model/Base_Model';
import Spinner from 'react-native-loading-spinner-overlay';
import MyStatusBar from './MyStatusBar';
import i18n from 'i18n-js';

class EmailConfirmation extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            confirmation_number: "",
            spinner: false,
            caretHidden:true,
        }
    }

    componentDidMount() {
        console.log("SESSION   " + this.props.pageEmailConfirmation)
    }

    handleSubmit() {
        this.setState({
            spinner: true,
        })
        // console.log(this.props.isEmailverif)
        if (this.props.isEmailverif === true) {
            let pageProps = {
                pageEmailConfirmation: false
            }
            this.props.setPage(pageProps)
            // console.log('hai ini gue kalau ada device yang sama!')

            let params = {
                "session_id": this.props.session_id,
                "email": this.props.email,
                "password": this.props.password,
                "fb_token": this.props.fb_token,
                "device_id": this.props.device_id,
                "os_name": this.props.os_name,
                "os_version": this.props.os_version,
                "app_version": this.props.app_version,
                "verification_code": this.state.confirmation_number
            }
            Axios.post(this.props.BASE_URL+'crm/v2/auth/login', params).then(res => {
                // console.log('EMAIL CONFIRM : ' + JSON.stringify(res))
                let emailConfirmProps = {
                    isEmailverif: false
                }
                let loginProps = {
                    email: this.props.email,
                    password: this.props.password,
                    session_id: res.data.session_id
                }

                // console.log('LOGIN PROPS : ' + JSON.stringify(loginProps))

                this.props.setLoginInfo(loginProps)
                this.props.setEmailConfirm(emailConfirmProps)
                this.setState({
                    spinner: false,
                })
                this.props.navigation.reset({
                    index: 0,
                    routes: [
                        {
                            name: 'Welcome log',
                        },
                    ],
                })
            }).catch(error => {
                let response = error.response.data;
                Alert.alert('',response.msg);
                this.setState({
                    spinner: false,
                })
            })

        } else {

            let pageProps = {
                pageEmailConfirmation: false
            }
            this.props.setPage(pageProps)
            let paramater = {
                "email": this.props.email,
                "confirmation_number": this.state.confirmation_number,
            }
            Axios.post(this.props.BASE_URL+'crm/v2/auth/register_confirm', paramater).then(res => {
                this.setState({
                    spinner: false,
                })
                console.log('masuk pak eko')
                // this.props.navigation.reset("Login");
                this.props.navigation.reset({
                    index: 0,
                    routes: [
                        {
                            name: 'Welcomes',
                        },
                    ],
                })

            }).catch(error => {
                this.setState({
                    spinner: false,
                })
                let response = error.response.data;
                Alert.alert(response.msg);
            })
        }
    }

    handleCancel() {
        if (this.props.proses !== 'Register') {
            let pageProps = {
                isEmailverif: false
            }
            this.props.setPage(pageProps)
            this.props.navigation.navigate('Login');
        } else {
            let pageProps = {
                isEmailverif: false
            }
            this.props.setPage(pageProps)
            this.props.navigation.navigate('New Register');
        }

    }

    handleResend() {
        this.setState({
            spinner: true,
        })

        if (this.props.proses !== 'Register') {
            let params = {
                "email": this.props.email,
                "password": this.props.password,
                "fb_token": this.props.fb_token,
                "device_id": this.props.device_id,
                "os_name": this.props.os_name,
                "os_version": this.props.os_version,
                "app_version": this.props.app_version,
            }
            // console.log(params)
            Axios.post(this.props.BASE_URL+'crm/v2/auth/login', params).then(res => {

                this.setState({
                    spinner: false,
                })

            }).catch(error => {

                let response = error.response.data;
                Alert.alert('', 'Silahkan Cek Email Kembali');
                this.setState({
                    spinner: false,
                })

            })
        } else {
            let paramater = {
                "email": this.props.email,
                "registration_id": this.props.registration_id,
            }
            let pageProps = {
                pageEmailConfirmation: false
            }
            this.props.setPage(pageProps)

            Axios.post(this.props.BASE_URL+'crm/v2/auth/register_resend_email', paramater).then(res => {
                this.setState({
                    spinner: false,
                })
                Alert.alert(
                    'Sukses',
                    'Email berhasil di kirimkan! '

                )
            }).catch(error => {

                let response = error.response.data;
                // console.log(response);
                this.setState({
                    spinner: false,
                })
                Alert.alert('', response.msg)
            })
        }

    }

    render() {
        console.log(this.props.proses)
        return (
            <View style={styles.container}>
                <MyStatusBar />
                <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                />
                <View style={{ flex: 3 }}>
                    <View style={{ flex: 1, marginRight: 30, marginLeft: 30, top: 60 }}>
                        <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 20, textAlign: 'center', margin: 3 }}>Token</Text>
                        <TextInput style={{ height: 40, borderWidth: 1, padding: 5, margin: 10, borderRadius: 10, borderColor: 'grey', fontFamily: 'Gotham-Black', textAlign: 'center', color: 'grey', fontWeight: 'bold', fontSize: 20 }}
                            onChangeText={(confirmation_number) => this.setState({ confirmation_number })}
                            value={this.state.confirmation_number}
                            autoCapitalize="none"
                            value={this.state.email}
                            keyboardType='numeric'
                            caretHidden={this.state.caretHidden}
                            onFocus={() => this.setState({caretHidden: false})} />
                        <TouchableOpacity style={{ height: 100 }} onPress={() => this.handleSubmit()}>
                            <View style={{ backgroundColor: '#CFB368', height: 45, top: 10, borderRadius: 10, marginRight: 50, marginLeft: 50 }}>
                                <Text style={{ alignSelf: 'center', top: 10, color: 'white', fontFamily: 'Gotham-Black', fontSize: 20 }}>{i18n.t('submit')}</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity style={{ height: 100 }} onPress={() => this.handleCancel()}>
                            <View style={{ backgroundColor: '#CFB368', height: 45, top: 10, borderRadius: 10, marginRight: 50, marginLeft: 50 }}>
                                <Text style={{ alignSelf: 'center', top: 10, color: 'white', fontFamily: 'Gotham-Black', fontSize: 20 }}>{i18n.t('cancel')}</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity style={{ height: 60 }} onPress={() => this.handleResend()}>
                            <Text style={{ alignSelf: 'center', color: '#CFB368', fontFamily: 'Gotham-Black', fontSize: 20, top: 10 }}>{i18n.t('resendemail')}</Text>
                        </TouchableOpacity>
                        {this.props.proses == 'Register' ? (
                            <TouchableOpacity style={{ height: 60 }} onPress={() => this.props.navigation.navigate('Change Email')}>
                                <Text style={{ alignSelf: 'center', color: '#CFB368', fontFamily: 'Gotham-Black', fontSize: 20, }}>{i18n.t('changeEmail')}</Text>
                            </TouchableOpacity>
                        ) : (null)}
                    </View>
                </View>
                <View style={{ flex: 1, flexDirection: 'row' }}>
                    <View style={styles.v_logo}>
                        <View style={{ flex: 1, alignSelf: 'flex-start' }}>
                            <Image resizeMode="contain" source={require('../assets/images/daun.png')} style={styles.logo}></Image>
                        </View>
                        <View style={{ flex: 1 }}>

                        </View>
                    </View>

                    <View style={{ flex: 0.5 }}>
                    </View>
                </View>
            </View>
        )
    }
}


const styles = StyleSheet.create({

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

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

    form: {
        flex: 3,
        top: 40,
        margin: 10,
        marginTop: 0,
    },

    field_email: {
        flexDirection: 'row'
    },

    button: {
        height: 40,
        margin: 10,

    },
    logo: {
        alignSelf: 'flex-start',
        marginTop: 50,
        width: 290,
        height: 290,
        bottom: 145,

    },
    v_logo: {
        flex: 2,
        flexDirection: 'column-reverse',
        alignContent: 'flex-start',
    }
})

const mapStateToProps = (state) => {
    // console.log('EMAIL CONFIRM : ' + JSON.stringify(state))
    return {
        isEmailverif: state.isEmailverif,
        email: state.email,
        session_id: state.session_id,
        password: state.password,
        fb_token: state.fb_token,
        device_id: state.device_id,
        os_version: state.os_version,
        os_name: state.os_name,
        app_version: state.app_version,
        page: state.page,
        registration_id: state.registration_id,
        pageEmailConfirmation: state.pageEmailConfirmation,
        proses: state.proses,
        language: state.language,
        BASE_URL: state.BASE_URL
    }
}

const mapDispatchToProps = (dispacth) => {
    return {

        setEmailConfirm: (emailConfirmProps) => dispacth({
            type: ActionType.SET_EMAIL_VERIFICATION,
            data: {
                isEmailverif: emailConfirmProps.isEmailverif,
            }
        }),
        setProses: (prosesProps) => dispacth({
            type: ActionType.SET_PROSES,
            data: {
                proses: prosesProps.proses
            }
        }),
        setLoginInfo: (loginProps) => dispacth({
            type: ActionType.SET_LOGIN_INFO,
            data: {
                email: loginProps.email,
                password: loginProps.password,
                session_id: loginProps.session_id
            }
        }),
        setPage: (pageProps) => dispacth({
            type: ActionType.SET_PAGE,
            data: {
                pageEmailConfirmation: pageProps.pageEmailConfirmation
            }
        }),
    }
}


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


{/* <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                />
                <View style={{ margin: 10, top: 10 }}>
                    <TextInput
                        style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 5 }}
                        onChangeText={(confirmation_number) => this.setState({ confirmation_number })}
                        value={this.state.confirmation_number}
                    />
                </View>
                <View style={{ margin: 10 }}>
                    <Button title="Submit" onPress={() => this.handleSubmit()} />
                </View>
                <View style={{ margin: 10 }}>
                    <Button title="Cancel" onPress={() => this.handleCancel()} />
                </View>
                <View>
                    <TouchableOpacity onPress={() => this.handleResend()}>
                        <Text style={{ color: 'red', textAlign: 'center' }}>Resend email token</Text>
                    </TouchableOpacity>
                </View>
                <View>
                    <TouchableOpacity onPress={() => this.props.navigation.navigate('Change Email')}>
                        <Text style={{ color: 'red', textAlign: 'center' }}> Change email</Text>
                    </TouchableOpacity>
                </View> */}