import * as React from 'react';
import { Button, View, Text, TextInput, StyleSheet, Alert, Platform, Image, TouchableOpacity, StatusBar, ImageBackground, ScrollView } from 'react-native';
import Axios from 'axios';
import Constants from 'expo-constants';
import * as Device from 'expo-device';
import * as Permissions from 'expo-permissions';
import * as Application from 'expo-application';
import { connect } from 'react-redux';
import ActionType from '../redux/globalActionType';
import { BASE_URL_LOGIN } from '../model/Base_Model';
import { Notifications } from 'expo';
import Spinner from 'react-native-loading-spinner-overlay';
import Toast from 'react-native-tiny-toast';
import CheckVersion from '../function/CheckVersion';

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() {
        const { navigation } = this.props
        console.log(this.props.navigation)
        CheckVersion(navigation)
        this._getDeviceInfo()
    }

    _getDeviceInfo = async () => {
        if (Constants.isDevice) {
            const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
            let finalStatus = existingStatus;
            if (existingStatus !== 'granted') {
                const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
                finalStatus = status;
            }
            if (finalStatus !== 'granted') {
                Toast.show('Failed to get push token for push notification!');
                return;
            }

            let fb_token = await Notifications.getExpoPushTokenAsync();
            let device_id = Constants.deviceId
            let os_name = Device.osName
            let os_version = Device.osVersion
            let app_version = Constants.manifest.version

            let deviceInfoProps = {
                device_id: device_id,
                os_name: os_name,
                fb_token: fb_token,
                os_version: os_version,
                app_version: app_version
            }
            // console.log(deviceInfoProps);
            this.props.setDeviceInfo(deviceInfoProps)
        } else {
            Toast.show('Must use physical device for Push Notifications');
        }
    }

    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.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(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: ''
                }

                this.props.setProses(prosesProps);
                this.props.setLoginInfo(loginProps);
                this.setState({
                    spinner: false,
                })

                navigation.reset({
                    index: 0,
                    routes: [
                        {
                            name: 'LoginWelcome',
                            params: { someParam: 'Param1' },
                        },
                    ],
                })

            }).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
                    }
                    let prosesProps = {
                        proses: ''
                    }
    
                    this.props.setProses(prosesProps);

                    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() {

        // console.log(this.props.device_id)
        // console.log(this.props.os_name)
        // console.log(this.props.fb_token)
        // console.log(this.props.os_version)
        // console.log(this.props.app_version)
        return (
            <View style={styles.container}>
                <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                />
                <StatusBar hidden={true} />

                <ImageBackground source={require('../assets/images/loging-background.png')} style={{ width: '100%', height: '100%' }}>
                    <View style={styles.logo}>
                        <Image source={require('../assets/images/excelso-log.png')} style={styles.imageslogo}></Image>
                    </View>
                    <View style={styles.v_form}>
                        <View style={{ flex: 1, marginRight: 30, marginLeft: 30, justifyContent: 'center' }}  removeClippedSubviews={false} >
                            <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 20, textAlign: 'center', margin: 3 }}>Email</Text>
                            <TextInput
                                style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 10, borderRadius: 10, textAlign: 'center', fontFamily: 'Gotham-Black', color: 'white', fontSize: 13, fontWeight: 'bold' }}
                                onChangeText={(email) => this.setState({ email })}
                                autoCapitalize="none"
                                value={this.state.email}
                                keyboardType='email-address'
                                removeClippedSubviews={false}
                            />
                        </View>
                        <View style={{ flex: 1, height: 50, marginRight: 30, marginLeft: 30, justifyContent: 'center' }}>
                            <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 20, textAlign: 'center', margin: 3 }}>Password</Text>
                            <TextInput
                                style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 5, borderRadius: 10, textAlign: 'center', fontFamily: 'Gotham-Black', color: 'white', fontSize: 13, fontWeight: 'bold' }}
                                onChangeText={password => this.setState({ password })}
                                value={this.state.password}
                                secureTextEntry={true}
                                removeClippedSubviews={false}
                            />
                        </View>
                        <View style={{ flex: 1, height: 40, marginRight: 70, marginLeft: 70, justifyContent: 'center' }}>
                            <TouchableOpacity onPress={() => this.handleLoggin()}>
                                <View style={{ height: 50, borderRadius: 10, backgroundColor: '#CFB368' }}>
                                    <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center', margin: 15 }}>LOGIN</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View style={styles.v_policy}>
                        <View style={{ flex: 1, justifyContent: 'center' }}>
                            <TouchableOpacity onPress={() => this.props.navigation.navigate('New Register')}>
                                <Text style={{ fontFamily: 'Gotham-Light', color: '#CFB368', fontSize: 16, textAlign: 'center', marginBottom: 5 }}>REGISTER</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => this.props.navigation.navigate('Reset Password')}>
                                <Text style={{ fontFamily: 'Gotham-Light', color: '#CFB368', fontSize: 16, textAlign: 'center', marginTop: 5 }}>FORGOT PASSWORD</Text>
                            </TouchableOpacity>
                        </View>

                        <View style={{ flex: 1, justifyContent: 'center', marginRight: 60, marginLeft: 60 }}>

                            <Text style={{ fontFamily: 'Gotham-Light', color: '#CFB368', fontSize: 13, textAlign: 'center', marginBottom: 5 }}>
                                Dengan Login atau Register, Kamu menyetujui aturan <Text style={{ fontWeight: 'bold' }}> Panduan Layanan</Text> dan <Text style={{ fontWeight: 'bold' }}>Kebijakan Privasi kami</Text>
                            </Text>
                        </View>
                    </View>
                </ImageBackground>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#151515',
    },
    logo: {
        flex: 2.5,
        height: 50
    },
    imageslogo: {
        height: 150,
        margin: 10,
        width: 150,
        justifyContent: 'center',
        alignSelf: 'center',
        top: 50
    },
    v_form: {
        flex: 3,
        // borderColor: 'red',
        // borderWidth: 1,

    },
    v_policy: {
        flex: 2,
        // borderColor: 'red',
        // borderWidth: 1,
    }
})


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







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