import * as React from 'react';
import { Button, View, Text, TextInput, StyleSheet, Alert, Platform } from 'react-native';
import Axios from 'axios';
import Constants from 'expo-constants';
import { connect } from 'react-redux';
import ActionType from '../redux/globalActionType';
import { BASE_URL_LOGIN } from '../model/Base_Model';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { Notifications } from 'expo';
import i18n from 'i18n-js';
import { StackActions } from '@react-navigation/native';
import Spinner from 'react-native-loading-spinner-overlay';

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = ({
            email: "",
            password: "",
            fb_token: "",
            device_id: "",
            os_version: "",
            os_name: "",
            app_version: "",
            device_id: "",
            session_id: "",
            language: 'id',
            spinner: false,
        })
    }

    componentDidMount(){
        // console.log(this.props.language)
    }

    async handleLoggin() {
        if (/\s/.test(this.state.email)) {
            Alert.alert('Email tidak boleh mengandung spasi')
        } else {
        this.setState({
            spinner: true,
        })
        try {
            let device_id = Constants.deviceId
            let os_name = Constants.platform
            // let fb_token = await Notifications.getExpoPushTokenAsync();
            let os_version = Platform.Version

            if (this.props.device_id) {
                this.setState({
                    device_id: this.props.device_id,
                    os_name: os_name,
                    fb_token: fb_token,
                    os_version: os_version,

                })
            } else {
                let deviceInfoProps = {
                    device_id: device_id,
                    os_name: os_name,
                    fb_token: fb_token,
                    os_version: os_version,
                }
                // console.log(deviceInfoProps);
                this.props.setDeviceInfo(deviceInfoProps)
            }

        } catch (error) {

            let device_id = Constants.deviceId
            let os_name = Constants.platform
            let fb_token = await Notifications.getExpoPushTokenAsync();
            let os_version = Platform.Version

            if (this.props.device_id) {
                this.setState({
                    device_id: this.props.device_id,
                    os_name: os_name,
                    fb_token: fb_token,
                    os_version: os_version,

                })
            } else {
                let deviceInfoProps = {
                    device_id: device_id,
                    os_name: os_name,
                    os_version: os_version,
                    fb_token: fb_token,

                }
                this.props.setDeviceInfo(deviceInfoProps)
            }

            this.state.os_name = '';
            this.state.os_version = '';
            this.state.fb_token = '';
        }

        if (this.props.app_version) {
            this.setState({
                app_version: this.props.app_version
            })
        } else {
            this.setState({
                app_version: 'Unknown'
            })
        }

        //get request
        let params = {
            "email": this.state.email,
            "password": this.state.password,
            "fb_token": this.state.fb_token,
            "device_id": this.state.device_id,
            "os_name": this.state.os_name,
            "os_version": this.state.os_version,
            "app_version": this.state.app_version,
        }
        // console.log(params)
        Axios.post(BASE_URL_LOGIN, params).then(res => {

            const navigation = this.props.navigation

            let loginProps = {
                email: this.state.email,
                password: this.state.password,
                session_id: res.data.session_id
            }

            let prosesProps = {
                proses:'Register'
            }

            this.props.setProses(prosesProps);
            this.props.setLoginInfo(loginProps);
            this.setState({
                spinner: false,
            })
           
                navigation.reset({
                  index: 0,
                  routes: [
                    {
                      name: 'Home',
                      params: { someParam: 'Param1' },
                    },
                  ],
                })
              
           console.log("INI SESSION : " + this.props.session_id)

        }).catch(error => {

            let response = error.response.data;
            if (response.code === "NEED_VERIFICATION") {

                let loginProps = {
                    email: this.state.email,
                    password: this.state.password,  
                }
                let emailConfirmProps = {
                    isEmailverif: true
                }
                let pageProps = {
                    pageEmailConfirmation:true
                }

                this.props.setLoginInfo(loginProps)
                this.props.setEmailConfirm(emailConfirmProps)
                this.props.setPage(pageProps)
                this.setState({
                    spinner: false,
                })
                this.props.navigation.navigate('Email Confirmation')

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


    render() {
        return (
            <View style={styles.container}>
                <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                />
                <View style={styles.form}>
                    <View style={{ marginRight: 10, marginLeft: 10, }}>
                        <Text style={{ top: 5 }}>Email</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 5 }}
                            onChangeText={(email) => this.setState({ email })}
                            autoCapitalize="none"
                            value={this.state.email}
                            keyboardType='email-address'
                        />
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>{i18n.t('password')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 5 }}
                            onChangeText={password => this.setState({ password })}
                            value={this.state.password}
                            secureTextEntry={true}
                        />
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Button
                            title={i18n.t('login')}
                            onPress={() => this.handleLoggin()}
                        />
                    </View>
                </View>
                <View style={styles.footer}>
                    <View style={styles.container_register}>
                        <View style={{ flex: 1 }}>
                            <TouchableOpacity onPress={() => this.props.navigation.navigate('New Register')}>
                                <Text style={{ fontSize: 20 }}>{i18n.t('register')}</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={{ flex: 1, }}>
                            <TouchableOpacity onPress={() => this.props.navigation.navigate('Reset Password')}>
                                <Text style={{ fontSize: 20, textAlign: 'right' }}>{i18n.t('forgotPassword')}</Text>
                            </TouchableOpacity>
                        </View>

                    </View>
                </View>
            </View>
        )
    }
}

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

        flex: 6,
    },
    footer: {
        flex: 1,
    },
    container_register: {
        height: 50,
        flexDirection: 'row',
        margin: 10
    }
})


const mapDispatchToProps = (dispacth) => {
    return {
        setDeviceInfo: (deviceInfoProps) => dispacth({
            type: ActionType.SET_DEVICE_INFO,
            data: {

                fb_token: deviceInfoProps.fb_token,
                device_id: deviceInfoProps.device_id,
                os_version: deviceInfoProps.os_version,
                os_name: deviceInfoProps.os_name,
                app_version: deviceInfoProps.app_version,

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

const mapStateToProps = (state) => {
    return {

        email: state.email,
        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,
        language: state.language
    }
}

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