import React from 'react';
import { Redirect } from 'react-router-dom';

import { block } from 'bem-cn';
import directory from 'api2/directory';
import notify from 'lib2/notify';
import Modal from 'components2/Modal';
import { i18n } from 'i18n2';

const b = block('resource-remove-modal');

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

        this.state = {
            busy: false,
        };

        this._removeResource = this._removeResource.bind(this);
    }

    componentWillUnmount() {
        this._unmounted = true;
    }

    _removeResource() {
        const { serviceSlug, resourceId } = this.props;

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

        directory.send('DELETE', `/v11/resources/${encodeURIComponent(resourceId)}/`, {
            query: {
                service: serviceSlug,
            },
        })
            .then(({ ok, body }) => {
                if (!ok) {
                    return notify(
                        i18n(`backend_errors.${body.code}`) || this._getText('remove_resource_error'),
                        'error'
                    );
                }

                notify(
                    this._getText('remove_resource_success'),
                    'success'
                );

                this.setState({
                    redirect: true,
                });
            })
            .finally(() => {
                if (!this._unmounted) {
                    this.setState({
                        busy: false,
                    });
                }
            });
    }

    _getText(key, params) {
        const { serviceSlug } = this.props;

        return i18n(`resource_page.${serviceSlug}.${key}`, params) ||
            i18n(`resource_page.default.${key}`, params);
    }

    render() {
        let { visible, cls, onCancel, serviceSlug } = this.props;
        let { busy, redirect } = this.state;

        if (redirect) {
            return <Redirect to={`/portal/services/${serviceSlug}`} />;
        }

        return (
            <Modal
                cls={b({}).mix(cls)}
                visible={visible}
            >
                <Modal.Title>
                    {this._getText('remove_resource')}
                </Modal.Title>
                <Modal.CloseButton onClick={onCancel} />
                <Modal.Body>
                    {this._getText('remove_resource_warning')}
                </Modal.Body>
                <Modal.ConfirmActions
                    onConfirm={this._removeResource}
                    onCancel={onCancel}
                    confirmCaption={i18n('common.action.confirm')}
                />
                <Modal.Busy visible={busy} />
            </Modal>
        );
    }
}
