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 KEY_MAP = {
    long_name: 'full_name',
};

const ITEMS = [
    'long_name', 'phone', 'email',
    'postal_code', 'postal_address', 'legal_address',
    'inn', 'kpp', 'bik', 'account',
];

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

function getDefaultValues(storedValues) {
    const org = AuthStore.getOrganization();

    return _.assign({
        name: org.get('name'),
        phone: org.get('phone_number'),
        email: org.get('email'),
    }, storedValues);
}

const LegalPerson = 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.legal_person.${KEY_MAP[key] || 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.legal_person.placeholder.${KEY_MAP[key] || key}`)}
                    text={this.state.defaultValues[key]}
                />
            </Form.Item>
        );
    },

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

});

export default LegalPerson;
