/** Screen for creating default User Profile **/
import React from 'react';
import { Icon, FormInput, Alert, Linking } from 'react-native-elements';
import { Image, KeyboardAvoidingView, Platform, ScrollView, Text, View, Button, TouchableOpacity } from 'react-native';
import ImagePicker from 'react-native-image-picker';
import Permissions from 'react-native-permissions';

import { strings } from '../../../locales/i18n';
import { showFlashErrorMessage } from '../../../utils/errorHandler';
import { fetchAuth } from '../../../utils/fetch';

import endpoints from '../../../config/apiEndpoints';
import { toQueryString } from '../../../utils/aux';
import { FormLabel, Spacer, TextButton } from '../../../components/common';
import styles from './styles';

export default class SignupScreenFour extends React.Component {
    static navigationOptions = {
        title: strings('userCreateFlow.defaultProfileCreate.title'),
        headerStyle: { borderBottomWidth: 0 },
        headerTintColor: '#0D497E',
        headerRight: <Text style={styles.navigationHeaderRightStyle}>4/6</Text>
    };

    constructor(props) {
        super(props);
        this.state = {
            base64Img: null,
            cameraRollStatus: '',
            cameraStatus: '',
            loading: false,
            jobTitle: '',
            companyName: '',
            companyAddress: '',
            companyNumber: ''

        };

        this.openLinkedInWebView = this.openLinkedInWebView.bind(this);
        this.getLinkedInData = this.getLinkedInData.bind(this);
        this.getLinkedInAuthURL = this.getLinkedInAuthURL.bind(this);
        this.renderAvatarPhoto = this.renderAvatarPhoto.bind(this);
        this.launchPicker = this.launchPicker.bind(this);
    }

    onSaveButtonPress() {
        //this will be replaced with realm once it has been added so that we can persist the user data 
        //and send the object in this request
        this.props.navigation.navigate('signup5', { 
            jobTitle: this.state.jobTitle,
            companyName: this.state.companyName,
            companyAddress: this.state.companyAddress,
            companyNumber: this.state.companyNumber
        });
    }

    async onImageButtonPress(pickerMethod, pickerTypeState) {
        try {
            if (this.state[pickerTypeState] !== 'authorized') {
                const response = await Permissions.request('photo');
                if (response !== 'authorized') {
                    Alert.alert(strings(`common.error.permissionDenied_camera${pickerTypeState === 'cameraRollStatus' ? 'Roll' : ''}`));
                    Linking.openURL('app-settings:');
                    this.setState({ [pickerTypeState]: response });
                    return;
                } else if (response === 'authorized') {
                    const status = await Permissions.check('photo');
                    await this.launchPicker(pickerMethod, pickerTypeState, status);
                }
            }
        } catch (error) {
            console.log(error);
        }
    }

    // Network request to our API to get an OAuth token
    async getLinkedInAuthURL() {
        console.log('getting linkedin auth info');
        this.setState({ loading: true });
        console.log('sending fetch request');
        const result = await fetchAuth(endpoints.linkedInLogin);

        if (result.error) {
            showFlashErrorMessage(result.error);
            return null;
        }
        return result;
    }

    async getLinkedInData(linkedInAuthData) {
        try {
            const result = await fetchAuth(endpoints.retrieveLinkedInInfo(toQueryString(linkedInAuthData)));
            if (result.error) { 
                showFlashErrorMessage(result.error);
            } else {
                //this call will be altered once we gefull linkedin partner api access
                //this.setState({ profileInfo: result, loading: false });
            }
        } catch (error) {
            showFlashErrorMessage(error);
            this.setState({ loading: false });
        }    
    }

    // Navigates to a LinkedIn webview modal, when the auth creds are fetched successfully it will execute onSuccess
    async openLinkedInWebView() {
        console.log('linkedWebview Func hit');
        this.setState({ loading: true });

        try {
            const result = await this.getLinkedInAuthURL();
            this.setState({ loading: false });
            console.log('navigating to linkedin webview');
            this.props.navigation.navigate('linkedInWebView', { result, onSuccess: this.getLinkedInData });
        } catch (error) {
            showFlashErrorMessage(error);
            this.setState({ loading: false });
        }
    }

    async launchPicker(pickerMethod, pickerTypeState, status) {
        await ImagePicker[pickerMethod]({
            allowsEditing: true,
            mediaTypes: 'photo'
        }, (libraryResponse) => {
            if (libraryResponse.didCancel) {
                console.log('User cancelled image picker');
            } else if (libraryResponse.error) {
                console.log('ImagePicker Error: ', libraryResponse.error);
            } else if (libraryResponse.customButton) {
                console.log('User tapped custom button: ', libraryResponse.customButton);
            }
            this.setState({
                base64Img: libraryResponse.data,
                [pickerTypeState]: status
            });
        });
    }

    renderLinkedInButtons() {
        return (
            <TextButton
                rightText={strings('common.contactFields.linkedIn_import')}
                rightTextStyle={{ fontSize: 20, fontWeight: 'normal', color: styles.colors.grey }}
                containerStyle={{ marginLeft: -2, marginTop: 15 }}
                onPress={this.openLinkedInWebView}
                disabled
            />
        );
    }

    /**
    * Renders the avatar cirle on profiles
    **/
    renderAvatarPhoto() {
        if (this.state.base64Img) {
            return (
                <View style={styles.avatarStyle}>
                    <Image
                        source={{ uri: this.state.base64Img }}
                        style={styles.avatarStyle}
                    />
                    {this.renderPhotoButtons()}
                </View>
            );
        }

        // No profile Image
        return (
            <View style={styles.noAvatarStyle}>
                <Icon
                    name='account-circle'
                    size={150}
                    color={styles.colors.lightTeal}
                />
                {this.renderPhotoButtons()}
            </View>
        );
    }

    /**
     * Renders the photo buttons
     **/
    renderPhotoButtons() {
        const self = this;
        return (
            <View style={styles.buttonContainerStyle}>
                <TouchableOpacity
                onPress={this.onImageButtonPress.bind(self, 'launchImageLibrary', 'cameraRollStatus')}
                disabled={this.props.loading}
                >
                <Text style={styles.textButtonStyle}>{strings('common.buttons.uploadPhoto')}</Text>
                </TouchableOpacity>

                <Text style={styles.photoButtonsOrTextStyle}>{strings('profile.or')}</Text>

                <TouchableOpacity
                onPress={this.onImageButtonPress.bind(self, 'launchCamera', 'cameraStatus')}
                disabled={this.props.loading}
                >
                <Text style={styles.textButtonStyle}>{strings('common.buttons.takePhoto')}</Text>
                </TouchableOpacity>
            </View>
        );
    }

    renderInputComponents(labelString, inputPlaceholderText, onChangeInput) {
        return (
            <View>
                <FormLabel 
                    bold 
                    labelText={labelString} 
                    textStyle={styles.labelStyle}
                />
                <FormInput
                    underlineColorAndroid={styles.colors.greyBlue}
                    placeholder={inputPlaceholderText}
                    onChangeText={value => this.setState({ [onChangeInput]: value })}
                    style={styles.inputTextStyle}
                    autoCorrect={false}
                    autoCapitalize='none'
                />
            </View>
        );
    }


    renderContent() {
        return (
            <ScrollView contentContainerStyle={styles.parentContentScrollViewStyle} keyboardShouldPersistTaps="handled">
                <View style={{ flex: 1 }}>
                    {/* INSTRUCTIONS */}
                    <Text style={styles.instructions}>{strings('userCreateFlow.defaultProfileCreate.instructions')}</Text>    
                    <Spacer />
                    <View 
                        style={{ 
                          flex: 1,
                          flexDirection: 'column',
                          justifyContent: 'center'
                        }}
                    >
                        {this.renderAvatarPhoto()}
                        <Spacer />
                        {this.renderLinkedInButtons()}
                        {this.renderInputComponents(strings('common.contactFields.company_title_labelText'), strings('common.contactFields.company_title_placeholder'), 'jobTitle')}
                        {this.renderInputComponents(strings('common.contactFields.company_name_labelText'), strings('common.contactFields.company_name_placeholder'), 'companyName')}
                        {this.renderInputComponents(strings('common.contactFields.company_address_labelText'), strings('common.contactFields.company_address_placeholder'), 'companyAddress')}
                        {this.renderInputComponents(strings('common.contactFields.company_number_labelText'), strings('common.contactFields.company_number_placeholder'), 'companyNumber')}
                        <Text>{strings('userCreateFlow.defaultProfileCreate.no_verification_needed')}</Text>
                        <Spacer />
                    </View>
                </View>
                {/* SAVE AND CONTINUE BUTTON */}
                <Button
                    onPress={this.onSaveButtonPress.bind(this)}
                    title={strings('common.buttons.saveAndContinue')}
                    loading={this.state.loading}
                    style={styles.buttonStyle}
                    fontSize={20}
                />
            </ScrollView>
        );
    }

    /**
     * Render method
     **/
    render() {
        if (Platform.OS === 'android') {
            return this.renderContent();
        }

        // IOS
        return (
        <KeyboardAvoidingView
            style={{ flex: 1 }}
            keyboardVerticalOffset={90}
            behavior="padding"
        >
            {this.renderContent()}
        </KeyboardAvoidingView>
        );
    }
}
