import React from 'react';
import extend from 'extend';
import cancelablePromise from '../../utils/cancelable-promise';
import Heading from '../heading/heading.jsx';
import SubmitButton from './submit-button.jsx';
import Password from './password.jsx';
import classToObject from './class-to-object';
import serializeInput from './serialize-input';

const propTypes = {
    onChange: React.PropTypes.func.isRequired,
    onCancel: React.PropTypes.func.isRequired,
    onSubmit: React.PropTypes.func.isRequired,
    language: React.PropTypes.object.isRequired,
    fieldsWhitelist: React.PropTypes.array,
    showPasswordToggle: React.PropTypes.bool,
    formData: React.PropTypes.shape({
        firstName: React.PropTypes.string,
        lastName: React.PropTypes.string,
        phone: React.PropTypes.string,
        email: React.PropTypes.string,
        address: React.PropTypes.object
    })
};

export default class CustomerForm extends React.Component {

    static get defaultProps(){
        return {
            language: {},
            fieldsWhitelist: null,
            showPasswordToggle: true,
            formData: { address: {} }
        };
    }

    constructor(props) {
        super(props);
        this.cancelPromise = () => {};
        props.formData.address = classToObject(props.formData.address);
        var formData = props.formData;
        this.state = {
            isLoading: false,
            errorMessage: null,
            formData: {
                firstName: formData.firstName || '',
                lastName: formData.lastName || '',
                phone: formData.phone || '',
                email: formData.email || '',
                address: {
                    address: formData.address.address || '',
                    zipcode: formData.address.zipcode || '',
                    city: formData.address.city || '',
                    state: formData.address.state || '',
                    country: formData.address.country || ''
                }
            }
        };
    }

    onChange(event){
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;
        var formData = serializeInput(name, value);
        var merged = extend(true, {}, this.state.formData, formData);
        this.setState({formData: merged}, this.onChanged.bind(this));
    }

    onChanged(){
        this.props.onChange(this.state.formData);
    }

    onSubmit(event){
        event.preventDefault();

        this.setState({
            isLoading: true,
            errorMessage: null
        });
        /*
        return this.props.onSubmit(this.state.formData)
            .then(this.clearLoadingState.bind(this))
            .catch(this.setErrorState.bind(this));
        */
        const { formData } = this.state;
        const { onSubmit } = this.props;
        const nativePromise = onSubmit(formData);
        const { promise, cancel } = cancelablePromise(nativePromise);
        this.cancelPromise = cancel;
        return promise
            .then(this.clearLoadingState.bind(this))
            .catch(this.setErrorState.bind(this));
    }

    componentWillUnmount() {
        this.cancelPromise();
    }

    clearLoadingState(){
        this.setState({
            isLoading: false,
            errorMessage: null
        });
    }

    setErrorState(error){
        if(error.isCanceled) return;
        this.setState({
            isLoading: false,
            errorMessage: error.message
        });
    }

    clearErrorState(){
        this.setState({
            errorMessage: null
        });
    }

    className(){
        var modifier = this.state.isLoading ? 'customer-form--loading' : '';
        return `customer-form ${modifier}`;
    }

    isWhitelisted(name){
        const array = this.props.fieldsWhitelist;
        return !array || array.indexOf(name) !== -1;
    }

    render() {
        const { formData } = this.state;
        const onChange = this.onChange.bind(this);
        const onSubmit = this.onSubmit.bind(this);
        const { onCancel, language } = this.props;
        return (
            <form
                className={this.className()}
                onSubmit={onSubmit}>
                {language.heading && (
                    <header
                        className="customer-form__header">
                        <Heading text={language.heading} />
                    </header>
                )}
                <div className="customer-form__fields">
                    {this.isWhitelisted('firstName') && (
                        <input
                            className="customer-form__text-input"
                            type="text"
                            name="firstName"
                            value={formData.firstName}
                            onChange={onChange}
                            placeholder={language.firstNamePlaceholder} />
                    )}
                    {this.isWhitelisted('lastName') && (
                        <input
                            className="customer-form__text-input"
                            type="text"
                            name="lastName"
                            value={formData.lastName}
                            onChange={onChange}
                            placeholder={language.lastNamePlaceholder} />
                    )}
                    {this.isWhitelisted('address.address') && (
                        <input
                            className="customer-form__text-input"
                            type="text"
                            name="address.address"
                            value={formData.address.address}
                            onChange={onChange}
                            placeholder={language.addressPlaceholder} />
                    )}
                    {this.isWhitelisted('address.zipcode') && (
                        <input
                            className="customer-form__text-input"
                            type="text"
                            name="address.zipcode"
                            value={formData.address.zipcode}
                            onChange={onChange}
                            placeholder={language.postcodePlaceholder} />
                    )}
                    {this.isWhitelisted('address.city') && (
                        <input
                            className="customer-form__text-input"
                            type="text"
                            name="address.city"
                            value={formData.address.city}
                            onChange={onChange}
                            placeholder={language.cityPlaceholder} />
                    )}
                    {this.isWhitelisted('address.state') && (
                        <input
                            className="customer-form__text-input"
                            type="text"
                            name="address.state"
                            value={formData.address.state}
                            onChange={onChange}
                            placeholder={language.statePlaceholder} />
                    )}
                    {this.isWhitelisted('address.country') && (
                        <input
                            className="customer-form__text-input"
                            type="text"
                            name="address.country"
                            value={formData.address.country}
                            onChange={onChange}
                            placeholder={language.countryPlaceholder} />
                    )}
                    {this.isWhitelisted('phone') && (
                        <input
                            className="customer-form__text-input"
                            type="tel"
                            name="phone"
                            value={formData.phone}
                            onChange={onChange}
                            placeholder={language.phonePlaceholder} />
                    )}
                    {this.isWhitelisted('email') && (
                        <input
                            className="customer-form__text-input"
                            type="email"
                            name="email"
                            value={formData.email}
                            onChange={onChange}
                            placeholder={language.emailPlaceholder} />
                    )}
                </div>
                <Password
                    password={formData.password}
                    passwordRepeated={formData.passwordRepeated}
                    language={this.props.language}
                    showToggle={this.props.showPasswordToggle}
                    onChange={onChange} />
                <div className="customer-form__actions">
                    <SubmitButton
                        isLoading={this.state.isLoading}
                        errorMessage={this.state.errorMessage}
                        label={language.submit}
                        onErrorMessageClose={() => this.clearErrorState()} />
                    <button
                        type="button"
                        className="customer-form__cancel"
                        onClick={onCancel}>
                        {language.cancel}
                    </button>
                </div>
            </form>
        );
    }
}

CustomerForm.propTypes = propTypes;