import React from 'react';
import { block } from 'bem-cn';
import Scrollable from 'ui/Scrollable';
import StoreMixin from 'lib/StoreMixin';
import { i18n } from 'lib/i18n';
import Url from 'lib/Url';
import Metrika from 'lib/metrika';

import OrganizationStore from 'stores/Organizations';
import DomainStore from 'stores/Domains';
import DnsStore from 'stores/Dns';
import ConfigStore from 'stores/Config';
import PermissionStore from 'stores/Permissions';
import ModalActions from 'actions/Modal';
import OrgSettingsAppActions from 'actions/App/OrgSettings';

import EditForm from 'components/Dns/Forms/Edit';
import Button from 'lego-ui/Button';
import List from './List';
import DomainList from './Controls/DomainList';
import EditSoaRecord from './Controls/EditSoaRecord';

import './index.css';

const bDns = block('dns');

function getDomainList() {
    return DomainStore.getAll().map(domain => {
        const name = domain.getName();

        return { text: name, val: name };
    });
}

const Dns = React.createClass({

    mixins: [StoreMixin],

    getStoreState() {
        const nextState = {};

        if (this.state && this.state.selectedDomain) {
            nextState.selectedDomain = this.state.selectedDomain;
        }

        if (!nextState.selectedDomain) {
            nextState.selectedDomain = this.props.domain || DomainStore.getMasterDomain();
        }

        if (nextState.selectedDomain) {
            nextState.domain = DomainStore.getDomain(nextState.selectedDomain);
        } else {
            let domain = DomainStore.getAll()[0];

            if (domain) {
                nextState.domain = domain;
                nextState.selectedDomain = domain.getName();
            }
        }

        return nextState;
    },

    componentDidMount() {
        this.subscribe([OrganizationStore, DomainStore, DnsStore, PermissionStore]);

        if (this.props.domain) {
            this._handleDomainChange(this.props.domain);
        }
    },

    componentDidUpdate(prevProps) {
        if (prevProps.domain !== this.props.domain) {
            this._handleDomainChange(this.props.domain);
        }
    },

    _isEditable() {
        const { domain } = this.state;

        return PermissionStore.allowsDNSEditing() &&
            Boolean(domain && !domain.get('tech') && domain.get('owned'));
    },

    _handleDomainChange(value) {
        this.setState({
            isBusy: true,
        });

        OrgSettingsAppActions.showDns(value)
            .then(() => {
                this.setState({
                    selectedDomain: value,
                    domain: DomainStore.getDomain(value),
                });
            })
            .finally(() => {
                this.setState({
                    isBusy: false,
                });
            });
    },

    _handleAddClick() {
        const { domain } = this.state;

        Metrika.send('DNS', 'Клик Добавить');

        ModalActions.open({
            component: EditForm,
            props: {
                domain: domain ? domain.getName() : '?',
                onSubmit: this._handleCreateFormDone,
                onCancel: this._handleCreateFormDone,
            },
        });
    },

    _handleCreateFormDone() {
        ModalActions.close();
    },

    _renderDescription() {
        const { domain } = this.state;

        if (!domain) {
            return null;
        }

        const name = domain.getName();
        let content;

        if (this._isEditable()) {
            content = i18n('dns_settings.description');
        } else if (!domain.get('owned')) {
            content = i18n('dns_settings.not_editable.domain_must_be_owned', {
                domain: name,
                domain_verification_url: Url.getPath(`/admin/domains/${encodeURIComponent(name)}`),
            });
        } else if (domain.get('tech')) {
            content = i18n('dns_settings.not_editable.domain_must_be_natural', {
                domain: name,
            });
        }

        if (!content) {
            return null;
        }

        return (
            <div
                className="dns-description"
                dangerouslySetInnerHTML={{ __html: content }}
            />
        );
    },

    render() {
        const { domain, isBusy } = this.state;

        if (!domain) {
            return null;
        }

        const editable = this._isEditable();
        const component = {};

        if (editable) {
            component.add = (
                <Button
                    text={i18n('dns_settings.add_record')}
                    view="action"
                    onClick={this._handleAddClick}
                />
            );
            component.editSoaRecord = (
                <EditSoaRecord
                    domain={domain}
                />
            );
            component.warning = (
                <div
                    className="dns-warning"
                    dangerouslySetInnerHTML={{ __html: i18n('dns_settings.warning', {
                        dns_editor_help_url: ConfigStore.getUrl('ui.help.dns_editor'),
                        delegate_domain_help_url: ConfigStore.getUrl('ui.help.delegate_domain'),
                    }) }}
                />
            );
        }

        component.domain = (
            <DomainList
                options={getDomainList()}
                val={domain ? domain.getName() : null}
                size="l"
                onChange={this._handleDomainChange}
            />
        );

        component.list = (
            <List
                domain={domain}
                editable={editable}
                busy={isBusy}
            />
        );

        if (this.props.headless) {
            return (
                <div className={bDns({ headless: true })}>
                    {component.warning}
                    {this._renderDescription()}
                    <div className={bDns('controls')}>
                        {component.add}
                    </div>
                    {component.list}
                    {component.editSoaRecord}
                </div>
            );
        }

        return (
            <div className="dns-section card-section section">
                <div className="section-body">
                    <Scrollable>

                        <div className="dns-block">
                            <h1 className="dns-header">
                                {i18n('dns_settings.title')}
                            </h1>
                            <div className="dns-options">
                                {component.domain}
                                <div className="dns-controls">
                                    {component.add}
                                </div>
                            </div>
                            {component.warning}
                            {this._renderDescription()}
                            {component.list}
                            {component.editSoaRecord}
                        </div>

                    </Scrollable>
                </div>
            </div>
        );
    },

});

export default Dns;
