import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import Button from 'react-bem-components/lib/Button';
import Form from 'ui/Form';
import FormMixin from 'lib/FormMixin';

import GroupStore from 'stores/Groups';
import GroupActions from 'actions/Group';
import groupValidator from 'validation/group';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';
import filterInput from './filterInput';
import Members from './Components/Members';
import Admins from './Components/Admins';

import './index.css';

const METRIKA_MAP = {
    admins: 'Список администраторов',
    members: 'Список пользователей',
};

const AddMembers = React.createClass({

    mixins: [FormMixin],

    getInitialState() {
        return {
            selectedItems: [],
            errors: groupValidator.getErrors(),
        };
    },

    componentDidMount() {
        this.refs.itemPicker.focus();
    },

    _handleFormSubmit(data) {
        const group = GroupStore.get(this.props.id);

        if (group) {
            if (data.selected_admins) {
                data.admins = JSON.parse(_.unescape(data.selected_admins))
                    .concat(group.getAdmins().map(
                        x => x ? { id: x.getId() } : null
                    ))
                    .filter(Boolean);
                delete data.selected_admins;
            }

            if (data.selected_members) {
                data.members = JSON.parse(_.unescape(data.selected_members))
                    .concat(group.getMembers().map(
                        x => x ? { id: x.getId(), type: x.getType() } : null
                    ))
                    .filter(Boolean);
                delete data.selected_members;
            }
        }

        if (this._use(groupValidator, filterInput)._validate(data)) {
            Metrika.send(
                'Команды', 'Карточка команды', METRIKA_MAP[this.props.type],
                'Форма добавления', 'Добавить', Metrika.getUserType()
            );

            return this._submit(GroupActions.updateGroup(data, this.props.id), {
                success: i18n('group.status.members_updated'),
                failure: i18n('group.status.failed_to_update_members'),
            });
        }
    },

    _handleItemsChange(items) {
        this.setState({ selectedItems: items });
    },

    render() {
        const { id, type, onCancel } = this.props;
        const { selectedItems } = this.state;

        const errors = this.state.errors.toJS();
        const empty = !selectedItems.length;

        const group = GroupStore.get(id);
        const Items = type === 'admins' ? Admins : Members;

        return (
            <Form
                className="add-group-members-form form"
                onSubmit={this._handleFormSubmit}
            >

                <Items
                    ref="itemPicker"
                    group={group}
                    errors={errors}
                    onChange={this._handleItemsChange}
                />
                <Form.Error value={errors._common} mod="standalone" />

                <Form.Buttons mod="aligned">
                    <Button
                        text={i18n('common.action.add')}
                        type="submit"
                        disabled={empty}
                        view="action"
                    />
                    <Button
                        text={i18n('common.action.cancel')}
                        onClick={onCancel}
                    />
                </Form.Buttons>

            </Form>
        );
    },

});

AddMembers.propTypes = {
    id: PropTypes.string,
    type: PropTypes.string,
    onSubmit: PropTypes.func,
    onCancel: PropTypes.func,
};

export default AddMembers;
