import React from 'react';
import { block } from 'bem-cn';
import { Button } from 'lego-on-react';
import escape from 'lodash/escape';
import Modal from 'components2/Modal';
import InlineError from 'components2/InlineError';
import directory from 'api2/directory';
import metrika from 'api2/metrika';
import { SessionStore } from 'lib2/stores';
import onUrlHash from 'lib2/onUrlHash';
import getOrganization from 'lib2/getOrganization';
import hasPermission from 'lib2/hasPermission';
import { i18n } from 'i18n2';

import './index.css';

const b = block('leave-organization-modal');

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

        this.state = {
            visible: false,
        };

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

    componentDidMount() {
        this._hashListener = onUrlHash('#leave-organization', () => this.setState({ visible: true }));
    }

    componentWillUnmount() {
        this._unmounted = true;
        this._hashListener.remove();
    }

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

        metrika.send(
            'Покинуть организацию',
            'Клик',
        );

        directory
            .send('PATCH', `/v11/users/${SessionStore.get('user.id')}`, {
                body: JSON.stringify({
                    is_dismissed: true,
                }),
            })
            .then(({ ok, status, body }) => {
                metrika.send(
                    'Покинуть организацию',
                    ok ? 'Успешно' : 'Ошибка',
                );

                if (ok) {
                    window.location.href = window.location.origin;

                    return;
                }

                if (!this._unmounted) {
                    this.setState({
                        busy: false,
                        error: i18n(`backend_errors.users.${body.code}`) ||
                            i18n(`backend_errors.${body.code}`) ||
                            i18n('common.error.generic', { code: status }),
                    });
                }
            })
            .catch(() => {
                if (!this._unmounted) {
                    this.setState({ busy: false });
                }
            });
    }

    _onCancel() {
        this.setState({ visible: false });
    }

    _simulateClick(elem) {
        elem && elem.click();
    }

    render() {
        const { visible, busy, error } = this.state;

        if (!hasPermission('leave_organization')) {
            return null;
        }

        return (
            <Modal
                cls={b('modal')}
                visible={visible}
            >
                <Modal.Title>
                    {i18n('common_options.leave_organization')}
                </Modal.Title>
                <Modal.CloseButton onClick={this._onCancel} />
                <Modal.Body>
                    <div
                        className={b('content')}
                        ref={visible && this._simulateClick}
                        dangerouslySetInnerHTML={{
                            __html: i18n('user.message.confirm_dismissal.self', {
                                org_name: escape(getOrganization().name),
                            }),
                        }}
                    />
                    {error && (
                        <InlineError cls={b('error')}>
                            {error}
                        </InlineError>
                    )}
                </Modal.Body>
                <Modal.RightActions>
                    <Button
                        theme="pseudo"
                        size="m"
                        cls={b('button', { type: 'cancel' })}
                        onClick={this._onCancel}
                        focused
                    >
                        {i18n('common.action.cancel')}
                    </Button>
                    <Button
                        theme="action"
                        size="m"
                        cls={b('button', { type: 'confirm' })}
                        onClick={this._onConfirm}
                    >
                        {i18n('common.action.confirm')}
                    </Button>
                </Modal.RightActions>
                <Modal.Busy visible={busy} />
            </Modal>
        );
    }
}
