import React from 'react';
import {Image, Dimensions, StyleSheet, Text, ImageBackground, TextInput, View, TouchableOpacity,StatusBar} from 'react-native';
import LoadingModal from "./LoadingModal";
import Icon from './Icon'
import PropTypes from "prop-types";
import Orientation from "react-native-orientation-locker";

const dimensions = Dimensions.get('window');


export default class LoginScreen extends React.Component {

    state = {
        login: '',
        password: '',
        invalidCredentials: false,
        loading: false,
        secureTextEntry: true
    };

    componentDidMount() {
        Orientation.lockToPortrait();
    }

    componentWillUnmount() {
        Orientation.unlockAllOrientations();
        this.setState({loading: false});
    }

    async _login(){
        let success;
        try {
            if (this.state.login !== '' && this.state.password !== '') {
                this.setState({loading: true});
                success = await this.props.onPressLogin(this.state.login,this.state.password, () => this.setState({loading: false}));
            }
        } catch (e) {
            this.setState({loading: false});
            console.warn(e);
        }
        if(!success){
            this.setState({loading: false});
        }
    }

    renderLogin(){
        switch (this.props.loginLayout) {
            case 1:
                return (
                    <ImageBackground source={this.props.imageBackgroundPath} style={[styles.background, ]} blurRadius={this.props.ImageBackgroundBlur}>
                        <View style={[styles.formContainer, this.props.marginTop]}>
                            <View style={{paddingBottom: this.props.logoPaddingBottom}}>
                                <Image source={this.props.logoPath} resizeMode={this.props.logoResizeMode} style={{
                                    width: this.props.logoWidth, height: this.props.logoHeight,
                                }}/>
                            </View>

                            <View style={[styles.formInputsField]}>
                                <View style={{paddingBottom: 12}}>
                                    <TextInput
                                        placeholderTextColor={this.props.placeholderTextColor}
                                        underlineColorAndroid="transparent"
                                        textContentType='emailAddress'
                                        keyboardType='email-address'
                                        autoCapitalize='none'
                                        style={styles.formInput}
                                        placeholder={this.props.placeholderUser}
                                        keyboardAppearance="light"
                                        value={this.state.login}
                                        onChangeText={login => this.setState({login})}/>
                                </View>

                                <View style={{flexDirection: 'row'}}>
                                    <View style={{flex: 0.90}}>
                                        <TextInput
                                            placeholderTextColor={this.props.placeholderTextColor}
                                            underlineColorAndroid="transparent"
                                            secureTextEntry={this.state.secureTextEntry}
                                            autoCapitalize='none'
                                            textContentType='password'
                                            style={styles.formInput}
                                            placeholder={this.props.placeholderPassword}
                                            value={this.state.password}
                                            onChangeText={password => this.setState({password})}
                                        />
                                    </View>

                                    <TouchableOpacity style={{flex: 0.1, justifyContent: 'center', alignItems: 'flex-end', borderBottomColor: 'white'}} onPress={() => this.setState({secureTextEntry: !this.state.secureTextEntry})}>
                                        {this.state.secureTextEntry === true ?
                                            <Icon color={'white'} size={25} name={'visibility-off'} class={'MaterialIcons'}/>
                                            :
                                            <Icon color={'white'} size={25} name={'visibility'} class={'MaterialIcons'}/>
                                        }

                                    </TouchableOpacity>

                                </View>

                                {this.props.hasForgotPasswordButton ?
                                    <TouchableOpacity style={{alignItems: 'center', marginVertical: 12}}>
                                        <View>
                                            <Text style={[styles.alternativeButtonText, {color: this.props.placeholderTextColor}]}>{this.props.labelForgotPassword}</Text>
                                        </View>
                                    </TouchableOpacity>
                                    : undefined}
                                <TouchableOpacity  style={{paddingVertical: this.props.hasForgotPasswordButton ? 0 : 20}} onPress={async () => await this._login()}>
                                    <View style={[styles.submitButton, {backgroundColor: this.props.submitButtonColor}]}>
                                        <Text style={{color: 'white', fontSize: 24, padding: this.props.hasForgotPasswordButton ? 0 : 10}}>{this.props.labelLogin}</Text>
                                    </View>
                                </TouchableOpacity>


                                {this.props.labelError !== '' ?
                                    <Text style={{
                                        textAlign: 'center',
                                        color: 'red',
                                        paddingTop: 5
                                    }}>{this.props.labelError}</Text>
                                    : undefined}
                                {this.props.hasRegisterButton ?
                                    <TouchableOpacity onPress={() => this.props.onPressRegister()}
                                                      style={{alignItems: 'flex-end', padding: 15,}}>
                                        <View>
                                            <Text style={[styles.alternativeButtonText, {color: this.props.placeholderTextColor}]}>{this.props.labelRegister}</Text>
                                        </View>
                                    </TouchableOpacity>
                                    : undefined}
                            </View>
                        </View>
                    </ImageBackground>
                )
            case 2:
                return (
                    <ImageBackground source={this.props.imageBackgroundPath} style={{flex: 1, backgroundColor: 'transparent'}}>
                        <View style={{flex: 0.5,marginBottom: 0,marginTop: -10, justifyContent: 'flex-end', alignItems: 'center'}}>
                            <Image source={this.props.logoPath} resizeMode={'cover'} style={{width: dimensions.width*0.5, height: dimensions.width*0.5}}/>
                        </View>

                        <View

                            style={{flex: 0.5, padding: 30, justifyContent: 'flex-start', alignItems: 'flex-start'}}>


                            <View style={styles2.inputContainer}>
                                <View style={[styles2.iconContainer, { backgroundColor: this.props.themeColor}]}>
                                    <Icon class={"FontAwesome"} name={'user'} size={20} color={'white'}/>
                                </View>
                                <View style={styles2.textInputContainer}>
                                    <TextInput
                                        value={this.state.login}
                                        onChangeText={login => this.setState({login})}
                                        style={[styles2.textInput, {fontFamily: this.props.inputFontFamily}]}
                                        placeholder={this.props.placeholderUser}
                                        textContentType={'username'}
                                        autoCapitalize='none'
                                    />
                                </View>
                            </View>


                            <View style={styles2.inputContainer}>
                                <View style={[styles2.iconContainer, { backgroundColor: this.props.themeColor}]}>
                                    <Icon class={"MaterialIcons"} name={'lock'} size={20} color={'white'}/>
                                </View>
                                <View style={[styles2.textInputContainer, {flex: 1, flexDirection: 'row'}]}>
                                    <TextInput
                                        value={this.state.password}
                                        onChangeText={password => this.setState({password})}
                                        selectionColor={this.props.themeColor}
                                        underlineColor={this.props.themeColor}
                                        style={[styles2.textInput, {fontFamily: this.props.inputFontFamily, flex: 1}]}
                                        secureTextEntry={this.state.secureTextEntry}
                                        textContentType={'password'}
                                        autoCapitalize='none'
                                        placeholder={this.props.placeholderPassword}/>
                                    <TouchableOpacity style={{flex: 0.2, marginRight: 10, justifyContent: 'center', alignItems: 'flex-end', borderBottomColor: 'white'}} onPress={() => this.setState({secureTextEntry: !this.state.secureTextEntry})}>
                                        {this.state.secureTextEntry === true ?
                                            <Icon color={this.props.themeColor} size={25} name={'visibility-off'} class={'MaterialIcons'}/>
                                            :
                                            <Icon color={this.props.themeColor} size={25} name={'visibility'} class={'MaterialIcons'}/>
                                        }
                                    </TouchableOpacity>

                                </View>
                            </View>


                            <View style={{width: '100%',flexDirection: 'row',justifyContent: 'flex-end',   alignItems: 'flex-end', marginVertical: 10}}>
                                {/*<View style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>*/}
                                {/*    <Checkbox*/}
                                {/*        color={'green'}*/}
                                {/*        status={true}*/}
                                {/*        onPress={() => { this.setState({ checked: true }); }}*/}
                                {/*    />*/}
                                {/*    <Caption style={{fontFamily: 'Montserrat-ThinBold', marginTop: 0, paddingTop: 0, color: 'white'}}>Lembrar-me</Caption>*/}
                                {/*</View>*/}

                                <Text style={{color: 'white', fontFamily: this.props.additionalButtonsFontFamily, marginTop: 0, paddingTop: 0}}>{this.props.labelForgotPassword}</Text>
                            </View>

                            <TouchableOpacity
                                style={{backgroundColor: this.props.submitButtonColor, width: '100%', justifyContent: 'center',alignItems: 'center',padding: 14,marginTop: 10, borderRadius: 10}}
                                onPress={async () => await this._login()}>
                                <Text style={{fontFamily: this.props.loginFontFamily, color:'white', fontSize: 20}}>{this.props.labelLogin}</Text>
                            </TouchableOpacity>
                            {this.props.labelError !== '' ?
                                <Text style={{
                                    textAlign: 'center',
                                    color: 'red',
                                    alignSelf: 'center',
                                    paddingTop: 5
                                }}>{this.props.labelError}</Text>
                                : undefined}

                        </View>
                    </ImageBackground>
                )
        }

    }
    render() {
        return (
            <View style={{flex: 1}}>
                <StatusBar hidden />
                <LoadingModal isLoading={this.state.loading || this.props.loading} color={this.props.loadingColor}/>
                {this.renderLogin()}
            </View>

        );
    }
}

const styles = StyleSheet.create({
    formContainer: {
        marginHorizontal: 20,
        // marginTop: dimensions.height * 0.14,
        flexDirection: 'column',
        // backgroundColor: 'transparent',
        alignItems: 'center',
        justifyContent: 'center',
    },
    formInputsField: {
        width: (dimensions.width * 0.8),
    },
    formInput: {
        borderColor: '#ffffff',
        borderBottomWidth: 1,
        height: 60,
        padding: 6,
        marginTop: 0,
        color: '#ffffff',
        fontSize: 23
    },
    submitButton: {
        marginTop: 10,
        height: 45,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 4
    },
    alternativeButtonText: {
        color: '#d3d3d3',
        fontSize: 17
    },


    background: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    backgroundImage: {
        flex: 1,
    },

});


const styles2 = StyleSheet.create({
    iconContainer: {
        height:58,
        width: 50,
        borderBottomLeftRadius: 10,
        borderTopLeftRadius: 10,
        justifyContent: 'center',
        alignItems: 'center'

    },
    inputContainer: {flexDirection: 'row', paddingVertical: 20, paddingBottom: 0},
    textInputContainer: {flex: 1,backgroundColor: 'white', justifyContent: 'center', borderBottomRightRadius: 10, borderTopRightRadius: 10},
    textInput: {backgroundColor: 'white', fontSize: 18, paddingLeft: 10, borderBottomRightRadius: 10, borderTopRightRadius: 10}
})

LoginScreen.propTypes = {
    logoPath: PropTypes.number.isRequired,
    imageBackgroundPath: PropTypes.number.isRequired,
    placeholderTextColor: PropTypes.string,
    submitButtonColor: PropTypes.string,
    loadingColor: PropTypes.string,

    placeholderUser: PropTypes.string,
    placeholderPassword: PropTypes.string,

    labelForgotPassword: PropTypes.string,
    labelRegister: PropTypes.string,
    labelLogin: PropTypes.string,
    onPressForgotPassword: PropTypes.func,
    onPressRegister: PropTypes.func,
    onPressLogin: PropTypes.func.isRequired,

    hasError: PropTypes.bool,
    labelError: PropTypes.string,
    loading: PropTypes.bool,

    hasForgotPasswordButton: PropTypes.bool,
    hasRegisterButton: PropTypes.bool,
    ImageBackgroundBlur: PropTypes.number,

    logoWidth: PropTypes.number,
    logoHeight: PropTypes.number,
    logoPaddingBottom: PropTypes.number,
    logoResizeMode: PropTypes.string,
    marginTop: PropTypes.number,


    loginLayout: PropTypes.number,
    themeColor: PropTypes.string,
    loginFontFamily: PropTypes.string,
    additionalButtonsFontFamily: PropTypes.string

};

LoginScreen.defaultProps = {
    loginLayout: 1,
    placeholderTextColor: "#f0f0f0",
    submitButtonColor: "#0077B5",
    loadingColor: "#000000",
    placeholderUser: "Email",
    placeholderPassword: "Senha",
    labelForgotPassword: "Esqueceu sua senha?",
    labelRegister: "Cadastre-se",
    labelLogin: "Entrar",
    hasError: false,
    ImageBackgroundBlur: 1,
    hasForgotPasswordButton: true,
    hasRegisterButton: true,
    logoHeight: dimensions.height * 0.2,
    logoWidth: dimensions.width * 0.7,
    logoPaddingBottom: dimensions.height * 0.04,
    logoResizeMode: 'contain',
    labelError: '',
    loading: false,
    themeColor: 'black'
};

