import * as React from 'react';
import { Button, View, Text, StyleSheet, TextInput, Alert } 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';

class EmailConfirmation extends React.Component {

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

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

    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": 'uknown',
                "verification_code": this.state.confirmation_number
            }
            Axios.post(BASE_URL_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: 'Home',
                      },
                    ],
                  })
            }).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('https://excelsocrm.ravintoladev.com/crm/v2/auth/register_confirm', paramater).then(res => {
                this.setState({
                    spinner: false,
                })
                    // this.props.navigation.reset("Login");
                   this.props.navigation.reset({
                        index: 0,
                        routes: [
                          {
                            name: 'Login',
                          },
                        ],
                      })
                      
            }).catch(error => {
                this.setState({
                    spinner: false,
                })
                let response = error.response.data;
                Alert.alert(response.msg);
            })
        }
    }

    handleCancel(){
        let pageProps = {
            pageEmailConfirmation:false
        }
        this.props.setPage(pageProps)
        this.props.navigation.navigate('New Register');
    }

    handleResend() {
        this.setState({
            spinner: true,
        })
        let paramater = {
            "email": this.props.email,
            "registration_id": this.props.registration_id,
        }
        let pageProps = {
            pageEmailConfirmation:false
        }
        this.props.setPage(pageProps)

        Axios.post('https://excelsocrm.ravintoladev.com/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() {
        return (
            <View style={styles.container}>
                 <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>
            </View>
        )
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'
    }
})

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
    }
}

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);