import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import StoreMixin from 'lib/StoreMixin';

import { i18n } from 'lib/i18n';

import AuthStore from 'stores/Auth';
import SessionStore from 'stores/Sessions';
import UserStore from 'stores/Users';
import ConfigStore from 'stores/Config';
import SettingStore from 'stores/Settings';
import OrganizationStore from 'stores/Organizations';

import SenderActions from 'actions/Sender';
import SettingActions from 'actions/Settings';

import SubscribeNews from './SubscribeNews';

const serviceList = [
    'staff',
    'forms',
    'wiki',
    'disk',
];
const mailListSettingField = 'news_mail_subscription';
const mailListName = 'newsList';

const SubscribeNewsBox = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        const userId = AuthStore.getUserId();
        const user = UserStore.get(userId);
        const newState = {
            isConfirmed: SettingStore.getUserSetting(`${mailListSettingField}.confirm`) || false,
            services: serviceList.filter(service => AuthStore.isServiceEnabled(service)),
        };

        if (user) {
            newState.email = SessionStore.getUserEmail(userId);
        }

        return newState;
    },

    componentDidMount() {
        this.subscribe([UserStore, SettingStore, OrganizationStore]);
    },

    _onClickSubscribe() {
        const { email } = this.state;
        const senderData = {
            email,
            to_email: email,
            mail_list: mailListName,
            args: {
                lang: ConfigStore.get('app.locale'),
                tld: ConfigStore.get('app.tld'),
            },
        };

        this.setState({
            buttonLoading: true,
            error: null,
        });

        SenderActions.subscribeEmail(senderData)
            .then(({ errors }) => {
                if (errors) {
                    throw errors;
                }

                return SettingActions.updateSettings({ [mailListSettingField]: { confirm: true } });
            })
            .then(() => {
                this.setState({
                    buttonLoading: false,
                });

                this.props.next();
            })
            .catch(() => {
                this.setState({
                    buttonLoading: false,
                    error: i18n('onboarding.yo.error.common'),
                });
            });
    },

    _onClickSkip() {
        const { isConfirmed } = this.state;

        if (isConfirmed) {
            return this.props.next();
        }

        const mailListSettings = _.get(SettingStore.getUserSettings(), mailListSettingField, {});
        const newMailListSettings = _.assign(
            mailListSettings, { last_shown: Date.now() }
        );

        this.setState({
            globalLoading: true,
            error: null,
        });

        SettingActions.updateSettings({ [mailListSettingField]: newMailListSettings })
            .then(() => {
                this.setState({
                    globalLoading: false,
                });

                this.props.next();
            })
            .catch(() => {
                this.setState({
                    globalLoading: false,
                });

                this.props.next();
            });
    },

    render() {
        return (
            <SubscribeNews
                {...this.props}
                {...this.state}
                onSubscribe={this._onClickSubscribe}
                onSkip={this._onClickSkip}
            />
        );
    },
});

SubscribeNewsBox.propTypes = {
    next: PropTypes.func.isRequired,
    step: PropTypes.number,
};

export default SubscribeNewsBox;
