import _ from 'lodash';
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import { Button } from 'lego-on-react';
import StoreMixin from 'lib/StoreMixin';
import Scrollable from 'ui/Scrollable';
import { i18n } from 'lib/i18n';
import notify from 'services/notify';

import AuthStore from 'stores/Auth';
import SettingsStore from 'stores/Settings';
import OrganizationStore from 'stores/Organizations';
import OrgSettingsActions from 'actions/OrgSettings';

import HeaderType from './Components/HeaderType';
import PasswordChange from './Components/PasswordChange';

import './index.css';

const GeneralSettings = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        const org = AuthStore.getOrganization();

        let nextState = _.assign({}, this.state || {
            headerType: SettingsStore.getOrganizationSetting('header'),
            isPasswordChangeEnabled: org.get('can_users_change_password'),
        });

        if (!this._initialState) {
            this._initialState = _.clone(nextState);
            nextState.busy = false;
            nextState.hasChanges = false;
        }

        ['headerType', 'isPasswordChangeEnabled'].forEach(key => {
            if (this._initialState[key] === undefined) {
                this._initialState[key] = nextState[key];
            }
        });

        return nextState;
    },

    componentDidMount() {
        this.subscribe([AuthStore, OrganizationStore, SettingsStore]);
    },

    _submitChanges() {
        const { headerType, isPasswordChangeEnabled } = this.state;
        const data = {};

        if (headerType !== this._initialState.headerType) {
            data.header = headerType;
        }

        if (isPasswordChangeEnabled !== this._initialState.isPasswordChangeEnabled) {
            data.can_users_change_password = isPasswordChangeEnabled;
        }

        if (!Object.keys(data).length) {
            return;
        }

        this.setState({ busy: true });

        return OrgSettingsActions.update(data)
            .then(() => this._handleResolve('success'))
            .catch(() => this._handleResolve('error'));
    },

    _handleResolve(status) {
        this._initialState = null;
        this.setState(this.getStoreState());

        switch (status) {
            case 'success':
                notify(i18n('organization_settings.status.updated'), 'success');
                break;
            case 'error':
                notify(i18n('organization_settings.status.failed_to_update'), 'error');
                break;
        }
    },

    _handleChange(key, value) {
        const nextState = _.clone(this.state);

        nextState[key] = value;
        nextState.hasChanges = this._hasChanges(nextState);

        this.setState(nextState);
    },

    _hasChanges(nextState) {
        if (!this._initialState) {
            return false;
        }

        let hasChanges = false;

        ['headerType', 'isPasswordChangeEnabled'].forEach(key => {
            hasChanges |= this._initialState[key] !== (nextState || this.state)[key];
        });

        return Boolean(hasChanges);
    },

    render() {
        const { headerType, isPasswordChangeEnabled, busy, hasChanges } = this.state;

        return (
            <div className="general-settings section">
                <Scrollable>
                    <div className="section-body">
                        <h2 className="section-title">
                            {i18n('organization_settings.general_settings')}
                        </h2>
                        <div className="section-content">
                            <HeaderType
                                val={headerType}
                                busy={busy}
                                onChange={this._handleChange.bind(this, 'headerType')}
                            />
                            <PasswordChange
                                checked={isPasswordChangeEnabled}
                                busy={busy}
                                onChange={this._handleChange.bind(this, 'isPasswordChangeEnabled')}
                            />
                        </div>
                        <div className="section-actions">
                            <Button
                                theme="action"
                                view="default"
                                tone="default"
                                size="m"
                                disabled={!hasChanges || busy}
                                progress={busy}
                                onClick={this._submitChanges}
                            >
                                {i18n('common.action.save')}
                            </Button>
                        </div>
                    </div>
                </Scrollable>
            </div>
        );
    },

});

export default GeneralSettings;
