import { List } from 'immutable';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Picker, ScrollView, Text, TextInput, View } from 'react-native';
import { Avatar } from 'react-native-elements';

import { getEmailAvailability, getNomAvailability } from '../../api/profile.js';

import EditNomDeBid from './ProfileInputs/EditNomDeBid.js';
import EmailInput from './ProfileInputs/EmailInput.js';
import PasswordInput from './ProfileInputs/PasswordInput.js';
import PhoneListInput from './ProfileInputs/PhoneListInput.js';

import styles from './Profile.styles.js';

const STRINGS = {
    BUTTONS: {
        CANCEL: 'Cancel',
        SUBMIT: 'Register',
    },
    DEV: {
        FORM_INCOMPLETE_SUBMIT: 'Incomplete form... how did the button become enabled?',
    },
    ERRORS: {
        FORM_SUBMIT_ERRORS: 'Please complete all of the required fields. They have bold labels.',
    },
    HEADINGS: {
        AVATAR: 'Want to add a picture?',
        EMAIL: 'Email (this will be your username)',
        NOM: 'and a Nom de Bid - your bidding alias!',
        PASSWORD: 'For security, let\'s choose a password',
        PERSONAL: 'Great! And now a bit about you...',
    },
};

export default class CreateProfile extends Component {
    static get propTypes() {
        return {
            cancelEditAction: PropTypes.func.isRequired,
            saveProfileAction: PropTypes.func.isRequired,
        };
    }

    constructor(props) {
        super(props);

        this.state = {
            addresses: new List(),
            avatar: null,
            email: null,
            firstName: null,
            lastName: null,
            invalidEmail: null,
            nomDeBid: null,
            password: null,
            passwordMatch: false,
            phones: new List(),
        };

        this.handleCancel = this.handleCancel.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);

        this._handleValidPasswordEntry = this._handleValidPasswordEntry.bind(this);
    }

    _handleComponentStateUpdate(key, value) {
        this.setState({ [key]: value });
    }

    _handleValidPasswordEntry(password) {
        if (!password) {
            this.setState({ passwordMatch: false });
            return;
        }

        this.setState({ password, passwordMatch: true });
    }

    _validateEmail() {
        getEmailAvailability(this.state.email)
            .then((result) => {
                console.log(`_validateEmail => getEmailAvailability(${this.state.email}):`, result);
                this.setState({ invalidEmail: !result.available });
            });
    }

    getProfileFromState() {
        return {
            addresses: this.state.addresses.toArray(),
            avatar: this.state.avatar,
            email: this.state.email,
            firstName: this.state.firstName,
            lastName: this.state.lastName,
            nomDeBid: this.state.nomDeBid,
            password: this.state.password,
            phones: this.state.phones.toArray(),
        };
    }

    handleCancel() {
        this.props.cancelEditAction();
    }

    handleSubmit() {
        if (!this.isFormComplete()) {
            console.error(STRINGS.DEV.FORM_INCOMPLETE_SUBMIT);
            alert(STRINGS.ERRORS.FORM_SUBMIT_ERRORS);
            return;
        }

        this.props.saveProfileAction(this.getProfileFromState());
    }

    isFormComplete() {
        return (
            !!this.state.email &&
            !!this.state.firstName &&
            !!this.state.lastName &&
            !!this.state.email &&
            !!this.state.nomDeBid &&
            !!this.state.phones.size &&
            this.state.passwordMatch && !!this.state.password
        );
    }

    render() {
        const {
            addresses,
            avatar,
            email,
            firstName,
            lastName,
            nomDeBid,
            password,
            passwordMatch,
            phones
        } = this.state;

        return (
            <ScrollView style={styles.profileFormWrap}>
                <View style={[styles.sectionWrap, styles.emailWrap, styles.requiredWrap]}>
                    <Text style={styles.groupHeading}>{STRINGS.HEADINGS.EMAIL}</Text>
                    <EmailInput
                        handleValidEmailEntry={(email) => this.setState({ email })}
                        isRequired
                        showContinueButton
                    />
                    {email !== false && (
                        <Text style={{ color:'green', textAlign: 'center' }}>
                            {`Great, lets add a bit more detail...`}
                        </Text>
                    )}
                </View>
                {email !== null && (
                    <View style={[styles.sectionWrap, styles.nameWrap]}>
                        <Text style={styles.groupHeading}>{STRINGS.HEADINGS.PERSONAL}</Text>
                        <TextInput
                            onChange={(text) => this.setState({ firstName: text })}
                            placeholder="first name"
                            style={[styles.textInput, styles.requiredInput]}
                            value={this.state.firstName || ''}
                        />
                        <TextInput
                            onChange={(text) => this.setState({ lastName: text })}
                            placeholder="last name"
                            style={[styles.textInput, styles.requiredInput]}
                            value={this.state.lastName || ''}
                        />
                    </View>
                )}
                {firstName !== null && lastName !== null && (
                    <View style={[styles.sectionWrap, styles.password, styles.requiredWrap]}>
                        <Text style={styles.groupHeading}>{STRINGS.HEADINGS.PASSWORD}</Text>
                        <PasswordInput handleValidPasswordEntry={this._handleValidPasswordEntry} />
                    </View>
                )}
                {passwordMatch && (
                    <View style={[styles.sectionWrap, styles.nomWrap, styles.requiredWrap]}>
                        <Text style={styles.groupHeading}>{STRINGS.HEADINGS.NOM}</Text>
                        <EditNomDeBid
                            isStandalone
                            nomDeBid={this.state.nomDeBid}
                            updateNomDeBid={(nomDeBid) => this.setState({ nomDeBid })}
                        />
                    </View>
                )}
                {nomDeBid !== null && (
                    <View style={styles.rollDownPanel}>
                        <View style={[styles.sectionWrap, styles.phonesWrap]}>
                            <PhoneListInput
                                handleAdd={(phones) => this.setState({ phones })}
                                handleDelete={(phones) => this.setState({ phones })}
                                handleEdit={(phones) => this.setState({ phones })}
                                phones={phones}
                            />
                        </View>
                        <View style={[styles.sectionWrap, styles.addressesWrap]}>
                            {addresses !== null && addresses.size > 0 && (
                                /* LIST ADDRESSES */
                                <View />
                            )}
                            <Button title="Add address" onPress={() => false} />
                        </View>
                        <View style={[styles.sectionWrap, styles.avatarWrap]}>
                            <Text style={styles.groupHeading}>{STRINGS.AVATAR_HEADING}</Text>
                            {avatar !== null ? (
                                <Avatar source={{ uri: this.state.avatar }} showEditButton />
                            ) : (
                                <Avatar title={this.props.initials} showEditButton />
                            )}
                        </View>
                    </View>
                )}
                {phones.size > 0 && (
                    <View style={styles.register}>
                        <Button title={STRINGS.BUTTONS.SUBMIT} onPress={this.handleSubmit} />
                    </View>
                )}
                <View style={styles.cancelWrap}>
                    <Button title={STRINGS.BUTTONS.CANCEL} onPress={this.handleCancel} />
                </View>
            </ScrollView>
        );
    }
}
