/**
 * React Native Full App (https://store.enappd.com/product/react-native-full-app)
 *
 * Copyright © 2019-present Enappd. All rights reserved.
 *
 * This source code is licensed as per the terms found in the
 * LICENSE.md file in the root directory of this source tree.
 */
import React from 'react';
import { Form, Container, Content, Text, Button, Item, Body } from 'native-base';
import { Dimensions, KeyboardAvoidingView } from 'react-native';
import Constants from 'expo-constants';
import styles from './style';
import Firebase, { withFirebase } from '../../../firebase';
import InputBlock from '../../../components/firebase/InputBlock';
import ActionButton from '../../../components/firebase/ActionButton';
import { showToast } from '../../../utils';
import { FacebookLogin } from '../../../components/firebase/SocialLogin';
import AppIcon from '../../../components/firebase/AppIcon';
import { NavigationStackScreenProps } from 'react-navigation-stack';

interface Iprops extends NavigationStackScreenProps {
    firebase: Firebase;
}
interface Istate {
    email: string;
    password: string;
    isLoading: boolean
}

class LoginPage extends React.Component<Iprops, Istate> {
    constructor(props: Iprops) {
        super(props);
        this.state = {
            email: '',
            password: '',
            isLoading: false
        }
    }

    onChangeEmail = (email: string) => this.setState({ email })

    onChangePassword = (password: string) => this.setState({ password })

    gotoSignUp = () => {
        const { navigate } = this.props.navigation;
        navigate('SignUp')
    }
    doFacebookLogin = async (accessToken: string) => {
        try {

            const { user } = await this.props.firebase.loginWithFacebook(accessToken);
            const { uid, email, displayName } = user;
            const { exists } = await this.props.firebase.checkUserExists(uid);
            if (!exists) {
                // eslint-disable-next-line no-unneeded-ternary
                const name = displayName ? displayName : '';
                const userData = { email, name, uid };
                await this.props.firebase.createNewUser(userData);
            }
        } catch (e) {
            console.log(e, 'error in facebook login');
            if (e.message) {
                showToast(e.message);
            }
        }
    }

    gotoHome = async () => {
        this.setState({ isLoading: true });
        const { email, password } = this.state;
        try {
            const loginData = await this.props.firebase.signInWithEmailAndPassword(email, password);
            if (!loginData.code) {
                const { navigate } = this.props.navigation;
                navigate('App')
            }
        } catch (e) {
            console.log(e, 'error in login');
            if (e.message) {
                showToast(e.message);
            }
            this.setState({ isLoading: false });
        }
    }
    forgotPassword = () => this.props.navigation.navigate('ForgotPassword')
    render() {
        const {
            email,
            password,
            isLoading
        } = this.state;
        const disableAction = (email.length > 0 && password.length > 0);
        return (
            <Container>
                <KeyboardAvoidingView style={styles.KeyboardAvoidingView} >
                    <Content padder contentContainerStyle={styles.container}>
                        <AppIcon />
                        <Form>
                            <InputBlock
                                name='email'
                                onChangeText={this.onChangeEmail}
                                value={email}
                                disabled={isLoading}
                            />
                            <InputBlock
                                name='password'
                                onChangeText={this.onChangePassword}
                                value={password} disabled={isLoading}
                                type='password'
                            />
                            <Item style={styles.forgot}>
                                <Body>
                                    <Button transparent onPress={this.forgotPassword} style={styles.forgotButton}>
                                        <Text>Forgot Password ?</Text>
                                    </Button>
                                </Body>
                            </Item>
                            <ActionButton
                                onPress={this.gotoHome}
                                disabled={!disableAction}
                                displayText="login"
                                activityLoading={isLoading}
                            />
                        </Form>
                        <FacebookLogin afterAccessAction={this.doFacebookLogin} />
                        <Button
                            full rounded warning
                            style={styles.button}
                            onPress={this.gotoSignUp}
                        >
                            <Text>Don't have an account? Sign Up</Text>
                        </Button>
                    </Content>
                </KeyboardAvoidingView>
            </Container>
        );
    }
}

export default withFirebase(LoginPage);
