import React from 'react';
import { Button, Link, Icon } from 'lego-on-react';
import { block } from 'bem-cn';
import { BunkerStore, UserSettingsStore, ConfigStore } from 'lib2/stores';
import openUrl from 'lib2/openUrl';
import bunker from 'api2/bunker';
import settings, { saveSetting } from 'api2/settings';
import { i18n } from 'i18n2';

import './index.css';

const b = block('bunker-notification');

function toSettingsKey(id) {
    return `custom_survey_status_${id}`;
}

export default class extends React.PureComponent {
    constructor(props) {
        super(props);

        this.state = {
            closed: false,
        };

        this._update = this._update.bind(this);
        this._onConfirm = this._onConfirm.bind(this);
        this._onCancel = this._onCancel.bind(this);
    }

    componentDidMount() {
        this._update();

        this._storeListeners = [
            BunkerStore.onChange(this._update),
            UserSettingsStore.onChange(this._update),
        ];

        let { nodeKey } = this.props;
        let bunkerNodeData = BunkerStore.get(nodeKey);

        let prefetch;

        if (bunkerNodeData) {
            prefetch = Promise.resolve(bunkerNodeData);
        } else {
            prefetch = bunker.send('GET').then(({ body }) => {
                BunkerStore.mergeState(body);

                return body && body[nodeKey];
            });
        }

        prefetch.then(data => {
            let bunkerNodeId = data && data.id;

            if (bunkerNodeId && UserSettingsStore.get(toSettingsKey(bunkerNodeId)) === undefined) {
                return settings.send('GET').then(({ body }) => {
                    UserSettingsStore.mergeState(body);
                });
            }
        });
    }

    componentWillUnmount() {
        this._storeListeners.forEach(listener => listener.remove());
    }

    _update() {
        let bunkerNodeData = BunkerStore.get(this.props.nodeKey);
        let bunkerNodeId = (bunkerNodeData || {}).id;

        this.setState({
            _status: bunkerNodeId && UserSettingsStore.get(toSettingsKey(bunkerNodeId)),
            ...bunkerNodeData,
        });
    }

    _shouldRender() {
        const { isEnabled, text, _status, closed } = this.state;

        return isEnabled && !_status && text && !closed;
    }

    _onConfirm() {
        let { id, url } = this.state;
        let prefetch = Promise.resolve();

        this.setState({
            busy: true,
        });

        if (id) {
            prefetch = saveSetting(toSettingsKey(id), 'opened');
        }

        if (url) {
            prefetch.then(() => {
                openUrl(url[ConfigStore.get('app.tld')]);
            });
        }
    }

    _onCancel() {
        let { id } = this.state;

        if (id) {
            saveSetting(toSettingsKey(id), 'canceled');
        }

        this.setState({
            closed: true,
        });
    }

    render() {
        if (!this._shouldRender()) {
            return null;
        }

        let { text, button, busy } = this.state;
        let locale = ConfigStore.get('app.locale');

        return (
            <div className={b()}>
                <div className={b('content')}>
                    {text[locale]}
                </div>
                <Button
                    theme="action"
                    size="s"
                    cls={b('button', { role: 'accept' })}
                    onClick={this._onConfirm}
                    progress={busy}
                    disabled={busy}
                >
                    {button[locale] || i18n('common.action.ok')}
                </Button>
                <Link
                    theme="normal"
                    type="pseudo"
                    cls={b('close')}
                    onClick={this._onCancel}
                >
                    <Icon type="cross" />
                </Link>
            </div>
        );
    }
}
