import _ from 'lodash';
import React from 'react';
import block from 'bem-cn';
import { TextInput } from 'lego-on-react';
import FormMixin from 'lib/FormMixin';
import { i18n } from 'lib/i18n';
import AuthStore from 'stores/Auth';

import Form from 'ui/Form';

const ITEMS = [
    'last_name', 'first_name', 'middle_name',
    'phone', 'email',
];

const b = block('natural-person');

function getDefaultValues(storedValues) {
    const user = AuthStore.getUser();

    return _.assign({
        first_name: user.getFirstName(),
        last_name: user.getLastName(),
        middle_name: user.getMiddleName(),
        phone: user.getPhoneNumber(),
        email: user.getEmail(),
    }, storedValues);
}

const NaturalPerson = React.createClass({

    mixins: [FormMixin],

    getInitialState() {
        return {
            defaultValues: getDefaultValues(this.props.storedValues),
            text: '',
        };
    },

    _onInputChange(key, text) {
        this.setState(prevState => {
            const values = _.assign({}, prevState.defaultValues, { [key]: text });

            return { defaultValues: values };
        });
    },

    _renderItem(key) {
        return (
            <Form.Item
                key={key}
                label={i18n(`subscription.natural_person.${key}`)}
                errors={this.props.errors.get(_.camelCase(key))}
            >
                <TextInput
                    size="m"
                    autoComplete={false}
                    theme="normal"
                    view="default"
                    tone="default"
                    hasClear
                    name={key}
                    onChange={this._onInputChange.bind(this, key)}
                    placeholder={i18n(`subscription.natural_person.placeholder.${key}`)}
                    text={this.state.defaultValues[key]}
                />
            </Form.Item>
        );
    },

    render() {
        return (
            <div className={b()}>
                <input type="hidden" name="person_type" value="natural" />
                {ITEMS.map(this._renderItem)}
            </div>
        );
    },

});

export default NaturalPerson;
