import PropTypes from 'prop-types';
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import Button from 'react-bem-components/lib/Button';
import FormMixin from 'lib/FormMixin';
import AuthStore from 'stores/Auth';
import Url from 'lib/Url';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';

import Form from 'ui/Form';

import orgProfileValidator from 'validation/orgProfile';
import OrgProfileActions from 'actions/OrgProfile';
import Identity from './Components/Identity';
import Contacts from './Components/Contacts';
import LegalInfo from './Components/LegalInfo';

import filterInput from './filterInput';

const Update = React.createClass({

    mixins: [FormMixin, PureRenderMixin],

    getInitialState() {
        return { errors: orgProfileValidator.getErrors() };
    },

    componentWillReceiveProps() {
        this.setState(this.getInitialState());
    },

    _handleFormSubmit(data) {
        if (this._use(orgProfileValidator, filterInput)._validate(data)) {
            Metrika.send('Профиль организации', 'Редактирование', 'Сохранить');

            return this._submit(OrgProfileActions.updateInfo(data), {
                success: i18n('organization_profile.status.updated'),
                failure: i18n('organization_profile.status.failed_to_update'),
            });
        }
    },

    render() {
        const { onCancel } = this.props;
        const errors = this.state.errors.toJS();
        const organization = AuthStore.getOrganization();

        const sections = [
            <Identity organization={organization} errors={errors} key="identity" />,
            <Form.Separator key="separator1" />,
            <Contacts organization={organization} errors={errors} key="contacts" />,
        ];

        if (Url.getQueryParam('edit') === 'extended') {
            sections.push(
                <Form.Separator key="separator2" />,
                <LegalInfo organization={organization} errors={errors} key="legal_info" />
            );
        }

        return (
            <Form
                className="update-org-profile-form org-profile-form form"
                onSubmit={this._handleFormSubmit}
                autoComplete={false}
            >
                {sections}
                <Form.Error value={errors._common} mod="standalone" />
                <Form.Buttons mod="aligned">
                    <Button
                        text={i18n('organization_profile.action.update')}
                        view="action"
                        type="submit"
                    />
                    <Button
                        text={i18n('organization_profile.action.cancel')}
                        name="cancel"
                        onClick={onCancel}
                    />
                </Form.Buttons>
            </Form>
        );
    },

});

Update.propTypes = {
    onSubmit: PropTypes.func,
    onCancel: PropTypes.func,
};

export default Update;
