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 UIStore from 'stores/UI';
import GroupStore from 'stores/Groups';
import ApplicationStore from 'stores/Application';

import GroupActions from 'actions/Group';
import groupValidator from 'validation/group';

import { i18n } from 'lib/i18n';
import Url from 'lib/Url';
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 RemoveMembers = React.createClass({

    mixins: [FormMixin],

    getInitialState() {
        const { id, type } = this.props;

        return {
            selectedItems: UIStore.getSelectedGroupMembers(id, type),
            errors: groupValidator.getErrors(),
        };
    },

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

        const selectedItems = {};

        if (group) {
            if (data.selected_admins) {
                selectedItems.admins = JSON.parse(_.unescape(data.selected_admins));

                const admins = group.getAdmins().map(
                    x => x ? { id: x.getId() } : null
                ).filter(Boolean);

                _.remove(admins, item => Boolean(_.find(selectedItems.admins, item)));

                data.admins = admins;
                delete data.selected_admins;
            }

            if (data.selected_members) {
                selectedItems.members = JSON.parse(_.unescape(data.selected_members));

                const members = group.getMembers().map(
                    x => ({ id: x.getId(), type: x.getType() })
                );

                _.remove(members, item => Boolean(_.find(selectedItems.members, item)));

                data.members = members;
                delete data.selected_members;
            }
        }

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

            return this._submit(GroupActions.updateGroup(data, id), {
                success: i18n('group.status.members_updated'),
                failure: i18n('group.status.failed_to_update_members'),
            }).then(() => this._onSubmit(selectedItems));
        }
    },

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

    _onSubmit(selectedItems) {
        const currentObject = ApplicationStore.getSecondaryObject() || {};
        const filterObject = { id: currentObject.id };

        currentObject.roleGroup = _.get(currentObject, 'path[0]');

        if (currentObject.roleGroup !== 'admins') {
            filterObject.type = currentObject.type;
        }

        const filterObjectIndex = _.findIndex(selectedItems[currentObject.roleGroup], filterObject);

        // переходим в родительскую команду и закрываем карточку удаленного объекта
        if (filterObjectIndex !== -1) {
            Url.open(Url.getGroupPath('auto', this.props.id));
        }
    },

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

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

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

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

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

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

            </Form>
        );
    },

});

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

export default RemoveMembers;
