import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import classSet from 'classnames';
import Select from 'react-bem-components/lib/Select';
import { Permissions } from 'constants/Common';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';
import PermissionStore from 'stores/Permissions';

import Form from 'ui/Form';
import Input from 'ui/Input';
import Icon from 'ui/Icon';

const CONTACT_TYPES = [
    'email',
    'phone',
    'skype',
    'twitter',
    'icq',
    'telegram',
    'facebook',
    'site',
];

const CONTACT_TYPE_OPTIONS = CONTACT_TYPES.map(name => ({
    text: i18n(`user.contacts.${name.toLowerCase()}`) || _.capitalize(name),
    val: name,
}));

function isDisabled(user) {
    return !PermissionStore.contains(Permissions.EDIT_USER_CONTACTS, user);
}

const Contacts = React.createClass({

    getInitialState() {
        const { user } = this.props;
        let contacts = [];

        if (user) {
            contacts = user.getOrderedContacts();
        }

        return { contacts };
    },

    componentDidUpdate(prevProps, prevState) {
        const { contacts } = this.state;

        if (contacts.length !== prevState.contacts.length) {
            this.refs[`contact-${contacts.length - 1}`].focus();
        }
    },

    _handleAddClick(event) {
        event.preventDefault();

        Metrika.send('Карточка пользователя', 'Редактирование', 'Добавить поле');

        this.setState({
            // добавляем новый пустой контакт
            contacts: this.state.contacts.slice().concat([
                { type: null, value: '' },
            ]),
        });
    },

    _renderList() {
        const errors = this.props.errors.contacts || [];
        let errorIndex = 0;

        const items = this.state.contacts.map((contact, index) => {
            const name = {
                type: `contacts[${index}][type]`,
                value: `contacts[${index}][value]`,
            };
            let label;

            if (contact.type) {
                label = (
                    <Form.Label>
                        <input name={name.type} type="hidden" value={contact.type} />
                        {i18n(`user.contacts.${contact.type.toLowerCase()}`) || _.capitalize(contact.type)}
                    </Form.Label>
                );
            } else {
                label = (
                    <Form.Label mod="customizable">
                        <Select
                            options={CONTACT_TYPE_OPTIONS}
                            name={name.type}
                            width="available"
                            size="m"
                        />
                    </Form.Label>
                );
            }

            let itemErrors;

            // синтетические контакты неактивны и не участвуют в валидации
            // поэтому индекс в массиве ошибок ведем отдельно от индекса контактов
            if (!contact.synthetic) {
                itemErrors = errors[errorIndex++];
            }

            return (
                <Form.Item label={label} key={index} errors={itemErrors}>
                    <Input
                        ref={`contact-${index}`}
                        hasClear
                        name={name.value}
                        size="m"
                        val={contact.value}
                        disabled={contact.synthetic || isDisabled(this.props.user)}
                        width="available"
                    />
                </Form.Item>
            );
        });

        return items;
    },

    _renderAddButton() {
        return (
            <Form.Item className="user-form__add-item">
                <div className="user-form__add">
                    <span className="add-contact" onClick={this._handleAddClick}>
                        <Icon type="plus" />
                        {i18n('user.action.add_contact')}
                    </span>
                </div>
            </Form.Item>
        );
    },

    render() {
        const { contacts } = this.state;

        const className = classSet({
            form__subsection: true,
            'user-form__contacts': true,
            'user-form__contacts_full': contacts.length >= 10,
        });

        return (
            <div className={className}>
                {this._renderList()}
                {this._renderAddButton()}
            </div>
        );
    },
});

Contacts.propTypes = {
    user: PropTypes.object,
    errors: PropTypes.object,
};

Contacts.defaultProps = {
    errors: {},
};

export default Contacts;
