import React from 'react';
import { Link } from 'lego-on-react';

import { getCookie } from '@connect/cookies-lite';
import block from 'bem-cn';
import DocTitle from 'components2/DocTitle';
import ServiceSidebar from 'components2/ServiceSidebar';
import ResourceHeader from 'components2/ResourceHeader';
import DomainTitle from 'components2/DomainTitle';
import DomainStatus from 'components2/DomainStatus';
import DomainStatusDetails from 'components2/DomainStatusDetails';
import SetMasterDomainControl from 'components2/SetMasterDomainControl';
import RemoveDomainControl from 'components2/RemoveDomainControl';
import TabLink from 'components2/TabLink';
import DnsSettings from 'components2/DnsSettings';
import DomainVerification from 'components2/DomainVerification';
import DomainRestoration from 'components2/DomainRestoration';
import SpinOverlay from 'components2/SpinOverlay';

import { ConfigStore } from 'lib2/stores';
import getOrganization from 'lib2/getOrganization';
import hasPermission from 'lib2/hasPermission';
import getService from 'lib2/getService';
import isAdmin from 'lib2/isAdmin';
import fetchGendarmeData from 'lib2/fetchGendarmeData';
import fetchDomainOwnership from 'lib2/fetchDomainOwnership';
import openUrl from 'lib2/openUrl';

import directory from 'api2/directory';
import { i18n } from 'i18n2';
import './index.css';

const serviceSlug = 'webmaster';
const b = block('domain-page');

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

        this.state = {};

        this._update = this._update.bind(this);
        this._setDomain = this._setDomain.bind(this);
        this._onRemove = this._onRemove.bind(this);
    }

    componentDidMount() {
        this._update();
    }

    componentWillUnmount() {
        this._unmounted = true;
    }

    _setDomain(domain) {
        if (this._unmounted) {
            return Promise.resolve(domain);
        }

        return new Promise(resolve => {
            this.setState({ domain }, () => resolve(domain));
        });
    }

    _update() {
        let { name } = this.props;

        return directory
            .send('GET', '/v11/domains/', {
                query: {
                    name,
                    fields: 'master,tech,owned,name',
                },
            })
            .then(({ ok, body }) => {
                if (!ok || !body[0]) {
                    return this._setDomain({ name, missing: true });
                }

                return fetchGendarmeData(body[0]).then(this._setDomain);
            })
            .then(fetchDomainOwnership)
            .then(this._setDomain)
            .then(domain => {
                if (!domain) {
                    return;
                }

                let occupationWarningDismissed = Boolean(getCookie(`occupied_warning_${name}`));

                // если у неподтверждённого домена не запущена проверка владения,
                // проверяем, не занят ли он другой организацией;
                // если занят, покажем предупреждение (DIR-5547);
                // если предупреждение уже принято раньше, можно не проверять
                if (!domain.owned && !domain.last_check && !occupationWarningDismissed) {
                    return directory
                        .send('GET', '/v11/who-is/', {
                            query: {
                                domain: name,
                            },
                        })
                        .then(({ ok, body }) => {
                            if (ok && body && body[0]) {
                                return this._setDomain({
                                    ...domain,
                                    occupied: String(body[0].org_id) !== getOrganization().id,
                                });
                            }
                        });
                }
            })
            .finally(() => {
                if (!this._unmounted) {
                    this.setState({ inited: true });
                }
            });
    }

    _onRemove() {
        openUrl('/portal/services/webmaster');
    }

    _renderContent() {
        let { inited, busy, domain } = this.state;

        if (!inited || domain === undefined) {
            return (
                <div className={b('content')}>
                    <SpinOverlay
                        progress
                        size="m"
                        position="center"
                    />
                </div>
            );
        }

        let canViewDetails = isAdmin() && !domain.missing;

        return (
            <div className={b('content')}>
                {!domain.occupied && canViewDetails && (
                    <DomainStatusDetails
                        cls={b('status-details')}
                        domain={domain}
                    />
                )}
                <ResourceHeader
                    cls={b('header', { busy: false })}
                    serviceSlug={serviceSlug}
                    busy={false}
                    resource={{
                        name: (
                            <DomainTitle
                                cls={b('title')}
                                domain={domain}
                            />
                        ),
                        description: (
                            <DomainStatus
                                cls={b('status')}
                                domain={domain}
                                badge={false}
                                type="page"
                            />
                        ),
                    }}
                    actions={!domain.missing && [
                        <Link
                            cls={b('action', { type: 'go' })}
                            theme="normal"
                            url={ConfigStore.get('ui.relatedServices.webmaster')}
                            text={i18n('resource_page.webmaster.go')}
                            key="go"
                        />,
                        <SetMasterDomainControl
                            cls={b('action', { type: 'set_master' })}
                            domain={domain}
                            onSubmit={this._update}
                            trackId="webmaster.domains"
                            key="set_master"
                        />,
                        <RemoveDomainControl
                            cls={b('action', { type: 'remove' })}
                            domain={domain}
                            onSubmit={this._onRemove}
                            trackId="webmaster.domains"
                            key="remove"
                        />,
                    ]}
                />
                {domain.occupied && (
                    <DomainRestoration
                        cls={b('restoration')}
                        domain={domain}
                        onDomainTransfer={this._setDomain}
                    />
                )}
                {!domain.occupied && canViewDetails && (
                    <div className={b('tabs')}>
                        {!domain.owned && (
                            <React.Fragment>
                                <TabLink.Group>
                                    <TabLink url={window.location.pathname}>
                                        {i18n('domain.tabs.verification')}
                                    </TabLink>
                                </TabLink.Group>
                                <TabLink.Pane>
                                    <DomainVerification
                                        domain={domain}
                                        onVerified={this._update}
                                    />
                                </TabLink.Pane>
                            </React.Fragment>
                        )}
                        {domain.owned && (
                            <React.Fragment>
                                <TabLink.Group>
                                    <TabLink url={window.location.pathname}>
                                        {i18n('domain.tabs.dns')}
                                    </TabLink>
                                </TabLink.Group>
                                <TabLink.Pane>
                                    <DnsSettings
                                        domain={domain}
                                    />
                                </TabLink.Pane>
                            </React.Fragment>
                        )}
                    </div>
                )}
                <SpinOverlay
                    progress={busy}
                    size="m"
                    position="center"
                />
            </div>
        );
    }

    render() {
        const { name, cls } = this.props;
        const docTitle = `${name} / ${getService(serviceSlug).name} / ${i18n('common.full_main_title')}`;

        return (
            <div className={b({ slug: serviceSlug }).mix(cls)}>
                <DocTitle text={docTitle} />
                {hasPermission('use_connect') && (
                    <ServiceSidebar
                        cls={b('sidebar')}
                        serviceSlug={serviceSlug}
                    />
                )}
                {this._renderContent()}
            </div>
        );
    }
}
