import React from 'react';
import block from 'bem-cn';
import { Button } from 'lego-on-react';
import { i18n } from 'i18n2';
import directory from 'api2/directory';
import notify from 'lib2/notify';
import Modal from 'components2/Modal';
import SearchBox from 'components2/SearchBox';

import './index.css';

const b = block('service-responsible-modal');

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

        this.state = {
            busy: false,
            values: this._getValues(props),
            hasChanges: false,
        };

        this._onSearchBoxChange = this._onSearchBoxChange.bind(this);
        this._onSubmit = this._onSubmit.bind(this);
        this._onCancel = this._onCancel.bind(this);
    }

    componentDidUpdate(prevProps) {
        if (this.props.visible !== prevProps.visible) {
            this.setState({
                values: this._getValues(),
            });
        }
    }

    componentWillUnmount() {
        this._unmounted = true;
    }

    _getValues(props) {
        let { value } = props || this.props;
        let values = [];

        if (value) {
            values.push({ object: value, type: 'user' });
        }

        return values;
    }

    _onSearchBoxChange(items) {
        let { value } = this.props;
        let hasChanges = false;

        if (items[0]) {
            hasChanges = !value || String(value.id) !== String(items[0].object.id) || items[0].type !== 'user';
        }

        this.setState({
            values: items,
            hasChanges,
        });
    }

    _onCancel() {
        this.props.onCancel();

        this.setState({
            busy: false,
            values: this._getValues(),
            hasChanges: false,
        });
    }

    _onSubmit() {
        const { onConfirm, serviceSlug } = this.props;
        const { values } = this.state;

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

        directory.send('PATCH', `/v11/services/${serviceSlug}/`, {
            body: JSON.stringify({
                responsible_id: values && values[0].object ? Number(values[0].object.id) : 0,
            }),
        })
            .then(({ ok, body }) => {
                if (!ok) {
                    return notify(i18n('services.responsible.failed_to_update'), 'error');
                }

                notify(i18n('services.responsible.successfully_updated'), 'success');

                if (onConfirm) {
                    onConfirm(body.responsible_id);
                }
            })
            .finally(() => {
                if (!this._unmounted) {
                    this.setState({
                        busy: false,
                    });
                }
            });
    }

    render() {
        const { visible, cls, serviceSlug } = this.props;
        const { busy, values, hasChanges } = this.state;

        return (
            <Modal
                cls={b({}).mix(cls)}
                visible={visible}
            >
                <Modal.Title>
                    {i18n(`service_page.${serviceSlug}.responsible`) || i18n('service_page.default.responsible')}
                </Modal.Title>
                <Modal.CloseButton onClick={this._onCancel} />
                <Modal.Body>
                    <SearchBox
                        cls={b('search-box')}
                        limit={1}
                        values={values}
                        onChange={this._onSearchBoxChange}
                        searchType="user"
                    />
                </Modal.Body>
                <div className={b('actions')}>
                    <Button
                        cls={b('button', { type: 'save' })}
                        theme="action"
                        size="m"
                        disabled={!hasChanges}
                        onClick={this._onSubmit}
                        text={i18n('common.action.save')}
                    />
                    <Button
                        cls={b('button', { type: 'cancel' })}
                        theme="normal"
                        onClick={this._onCancel}
                        size="m"
                        text={i18n('common.action.cancel')}
                    />
                </div>
                <Modal.Busy visible={busy} />
            </Modal>
        );
    }
}
