import Axios from 'axios';
import { Notifications } from 'expo';
import Constants from 'expo-constants';
import * as Device from 'expo-device';
import * as Permissions from 'expo-permissions';
import i18n from 'i18n-js';
import * as React from 'react';
import { Alert, Image, ImageBackground, StatusBar, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { TouchableWithoutFeedback } from 'react-native-gesture-handler';
import Spinner from 'react-native-loading-spinner-overlay';
import Toast from 'react-native-tiny-toast';
import { connect } from 'react-redux';
import CheckVersion from '../function/CheckVersion';
import ActionType from '../redux/globalActionType';

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

    componentDidMount() {
        this.handleCheck()
        const { navigation } = this.props
        console.log(this.props.BASE_URL)
        CheckVersion(navigation)
        this._getDeviceInfo()
    }

    handleCheck() {
        if (this.props.pageEmailConfirmation === true) {
            this.props.navigation.replace('Email Confirmation');
        }
    }

    setBaseUrl() {
        if (this.state.clickSettings == 3) {
            this.props.navigation.navigate('Setting')
            this.setState({ clickSettings: 0 })
        } else {
            let new_count = this.state.clickSettings
            this.setState({ clickSettings: new_count + 1 })
        }
    }

    privacyPolicy() {
        // if (this.state.clickSettings == 3) {
        //     this.props.navigation.navigate('Setting')
        //     this.setState({ clickSettings: 0 })
        // } else {
        //     let new_count = this.state.clickSettings
        //     this.setState({ clickSettings: new_count + 1 })
        // }
        this.props.navigation.navigate('Privacy Statement')
    }

    _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(i18n.t('alertFailedGetTokenNotif'));
                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(i18n.t('alertMustPhysicalDevice'));
        }
    }

    async handleLoggin() {
        if (/\s/.test(this.state.email)) {
            Alert.alert('', i18n.t('alertSpaceCharEmail'))
        } 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": Constants.manifest.version,
                "build_number": Constants.manifest.extra.buildNumber
            }
            console.log(params)
            Axios.post(this.props.BASE_URL + 'crm/v2/auth/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: 'emailconfirm'
                }

                let pageProps = {
                    pageEmailConfirmation: false
                }

                let emailConfirmProps = {
                    isEmailverif: false
                }

                this.props.setPage(pageProps)
                this.props.setEmailConfirm(emailConfirmProps)
                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,
                        [
                            {
                                text: 'OK', onPress: () => 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 resizeMode="cover" source={require('../assets/images/excelso-log.png')} style={styles.imageslogo}></Image>
                            <TouchableWithoutFeedback style={{marginHorizontal:50, paddingVertical:20}} onPress={() => this.setBaseUrl()}/>                      
                    </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 }}>{i18n.t('email')}</Text>
                            <TextInput
                                caretHidden={this.state.caretHidden}
                                onFocus={() => this.setState({ caretHidden: false })}
                                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 }}>{i18n.t('password')}</Text>
                            <TextInput
                                caretHidden={this.state.caretHidden}
                                onFocus={() => this.setState({ caretHidden: false })}
                                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 }}>{i18n.t('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 }}>{i18n.t('register')}</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => this.props.navigation.navigate('Reset Password')}>
                                <Text style={{ fontFamily: 'Gotham-Light', color: '#CFB368', fontSize: 16, textAlign: 'center', marginTop: 5 }}>{i18n.t('forgotPassword')}</Text>
                            </TouchableOpacity>
                        </View>

                        <View style={{ flex: 1, justifyContent: 'center', marginRight: 60, marginLeft: 60 }}>
                            <TouchableWithoutFeedback onPress={() => this.privacyPolicy()}>
                                <Text style={{ fontFamily: 'Gotham-Light', color: '#CFB368', fontSize: 13, textAlign: 'center', marginBottom: 5 }}>
                                    {i18n.t('policy')} <Text style={{ fontWeight: 'bold' }}>{i18n.t('privacy')}</Text>
                                </Text>
                            </TouchableWithoutFeedback>
                        </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,
                email_confirm: pageProps.email_confirm
            }
        }),
    }
}

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,
        BASE_URL: state.BASE_URL,
        pageEmailConfirmation: state.pageEmailConfirmation
    }
}

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