import _get from 'lodash/get';
import React from 'react';
import { Link, Button, Icon } from 'lego-on-react';
import block from 'bem-cn';
import CircledPlusIcon from 'components/Icon/CircledPlus';
import LegacySidebar from 'components2/LegacySidebar';
import SpinOverlay from 'components2/SpinOverlay';
import OrgLogoPicker from 'components2/OrgLogoPicker';
import RemoveOrgLogoControl from 'components2/RemoveOrgLogoControl';
import RemoveOrgControl from 'components2/RemoveOrgControl';
import InlineEditable from 'components2/InlineEditable';
import getOrganization from 'lib2/getOrganization';
import isPartnerOrganization from 'lib2/isPartnerOrganization';
import isAdmin from 'lib2/isAdmin';
import isExternalAdmin from 'lib2/isExternalAdmin';
import hasPermission from 'lib2/hasPermission';
import hasOwnedDomains from 'lib2/hasOwnedDomains';
import pollStatus from 'lib2/pollStatus';
import notify from 'lib2/notify';
import { OrgStore } from 'lib2/stores';
import directory from 'api2/directory';
import copy from 'lib2/copy';
import { i18n } from 'i18n2';
import toEmail from './toEmail';
import updateOrgField from './updateOrgField';
import DEFAULT_LOGO from '../../../static/i/default-logo.png';
import './index.css';

const b = block('org-profile');

class OrgProfile extends React.Component {
    constructor() {
        super();

        this.state = {
            busy: true,
            org: getOrganization(),
        };

        this._update = this._update.bind(this);
        this._onOwnerChange = this._onOwnerChange.bind(this);
        this._submitOwner = this._submitOwner.bind(this);

        this._submitName = updateOrgField.bind(null, 'name');
        this._submitPhoneNumber = updateOrgField.bind(null, 'phone_number');
        this._submitEmail = updateOrgField.bind(null, 'email');
        this._submitFax = updateOrgField.bind(null, 'fax');
    }

    componentDidMount() {
        this._update();
        this._storeListener = OrgStore.onChange(this._update);

        directory
            .send('GET', '/v11/ui/org-profile')
            .then(({ ok, body }) => {
                if (ok) {
                    OrgStore.merge(getOrganization().id, body);
                }
            })
            .finally(() => {
                if (!this._unmounted) {
                    this.setState({
                        busy: false,
                    });
                }
            });
    }

    componentWillUnmount() {
        this._unmounted = false;
        this._storeListener.remove();
    }

    _update() {
        if (this._unmounted) {
            return;
        }

        let org = getOrganization();

        this.setState({
            org,
        });
    }

    _submitOwner(login) {
        let orgId = getOrganization().id;

        return directory
            .send('POST', `/v11/organizations/${orgId}/change-owner/`, {
                body: JSON.stringify({ login }),
            })
            .then(({ ok, body }) => {
                if (!ok) {
                    return { ok, body };
                }

                return pollStatus(`/v11/organizations/${orgId}/change-owner/`, {
                    query: {
                        task_id: body.task_id,
                    },
                });
            })
            .then(({ ok, body }) => {
                if (ok) {
                    notify(i18n('organization_profile.owner_updated'), 'success');

                    setTimeout(() => window.location.reload(), 5000);
                } else {
                    notify(i18n(`backend_errors.org.change_owner.${body.code}`) ||
                        i18n('common.status.failed'), 'error');
                }
            });
    }

    _onOwnerChange(ownerLogin) {
        this.setState({
            ownerLogin,
        });
    }

    _onOrgIdCopyClick = () => {
        if (copy(this.state.org.id)) {
            notify(i18n('common.status.copied'), 'success');
        }
    }

    render() {
        let { busy, org, ownerLogin } = this.state;
        let logoUrl = _get(org, 'logo.orig.url');
        let adminKey = isExternalAdmin() ? 'external' : 'internal';

        let canEdit = hasPermission('edit_organization');
        let canAddDomains = hasPermission('add_domains');

        if (busy) {
            return (
                <div className={b({ busy }).mix(this.props.cls)}>
                    <LegacySidebar />
                    <div className={b('content')}>
                        <SpinOverlay
                            position="center"
                            size="m"
                            progress
                        />
                    </div>
                </div>
            );
        }

        return (
            <div className={b({}).mix(this.props.cls)}>
                <LegacySidebar />
                <div
                    className={b('content')}
                    key={JSON.stringify(org)}
                >
                    <h1 className={b('main-title')}>
                        {i18n('sections.organization_profile')}
                    </h1>
                    <div className={b('logo')}>
                        <div className={b('logo-image-container', { empty: !logoUrl })}>
                            <img
                                src={logoUrl || DEFAULT_LOGO}
                                className={b('logo-image')}
                                height="60"
                                alt=""
                            />
                        </div>
                        {hasPermission('change_logo') && (
                            <div className={b('logo-controls')}>
                                <OrgLogoPicker
                                    cls={b('logo-control', { type: 'logo-picker' })}
                                    text={logoUrl ? i18n('logo.change_logo') : i18n('logo.set_logo')}
                                />
                                {logoUrl && (
                                    <RemoveOrgLogoControl
                                        cls={b('logo-control', { type: 'remove-logo' })}
                                    />
                                )}
                            </div>
                        )}
                    </div>
                    <div className={b('separator')} />
                    <div className={b('field', { type: 'name' })}>
                        <label className={b('label')}>
                            {i18n('organization_profile.name')}
                        </label>
                        <InlineEditable
                            cls={b('value')}
                            value={org.name}
                            onSubmit={this._submitName}
                            editable={canEdit}
                        />
                    </div>
                    <div className={b('field', { type: 'owner' })}>
                        <label className={b('label')}>
                            {i18n('organization_profile.owner.label')}
                        </label>
                        <InlineEditable
                            cls={b('value')}
                            value={toEmail(org.owner_login)}
                            hint={i18n('organization_profile.owner.tip')}
                            confirmType="warning"
                            confirmTitle={i18n('organization_profile.owner.warning.title')}
                            confirmMessage={i18n(`organization_profile.owner.warning.content.${adminKey}_owner`, {
                                email: toEmail(ownerLogin === undefined ? org.owner_login : ownerLogin),
                            })}
                            confirmButtonCaption={i18n('organization_profile.owner.warning.confirm')}
                            onChange={this._onOwnerChange}
                            onSubmit={this._submitOwner}
                            editable={hasPermission('change_owner')}
                        />
                    </div>
                    <div className={b('separator')} />
                    <h2 className={b('title', { type: 'contacts' })}>
                        {i18n('organization_profile.contacts._title')}
                    </h2>
                    <div className={b('field', { type: 'phone-number' })}>
                        <label className={b('label')}>
                            {i18n('organization_profile.contacts.phone_number')}
                        </label>
                        <InlineEditable
                            cls={b('value')}
                            value={org.phone_number}
                            onSubmit={this._submitPhoneNumber}
                            editable={canEdit}
                        />
                    </div>
                    <div className={b('field', { type: 'email' })}>
                        <label className={b('label')}>
                            {i18n('organization_profile.contacts.email')}
                        </label>
                        <InlineEditable
                            cls={b('value')}
                            value={org.email}
                            onSubmit={this._submitEmail}
                            editable={canEdit}
                        />
                    </div>
                    <div className={b('field', { type: 'fax' })}>
                        <label className={b('label')}>
                            {i18n('organization_profile.contacts.fax')}
                        </label>
                        <InlineEditable
                            cls={b('value')}
                            value={org.fax}
                            onSubmit={this._submitFax}
                            editable={canEdit}
                        />
                    </div>
                    <div className={b('separator')} />
                    <h2 className={b('title', { type: 'tech-details' })}>
                        {i18n('organization_profile.technical_details._title')}
                    </h2>
                    <div className={b('field', { type: 'org-id' })}>
                        <label className={b('label')}>
                            {i18n('organization_profile.technical_details.org_id')}
                        </label>
                        <div className={b('value')}>
                            {org.id}
                            {copy && (
                                <Button
                                    cls={b('copy')}
                                    theme="clear"
                                    size="xs"
                                    onClick={this._onOrgIdCopyClick}
                                >
                                    <Icon />
                                </Button>
                            )}
                        </div>
                    </div>
                    <div className={b('field', { type: 'domains' })}>
                        <label className={b('label')}>
                            {i18n('organization_profile.technical_details.natural_domains.title')}
                        </label>
                        {org.has_natural_domains && (
                            <div className={b('value')}>
                                {canAddDomains ? (
                                    <Link
                                        cls={b('link')}
                                        theme="normal"
                                        view="default"
                                        url="/portal/services/webmaster"
                                    >
                                        {i18n('organization_profile.technical_details.natural_domains.present')}
                                    </Link>
                                ) : i18n('organization_profile.technical_details.natural_domains.present')}
                            </div>
                        )}
                        {!org.has_natural_domains && (
                            <div className={b('value')}>
                                {i18n('organization_profile.technical_details.natural_domains.absent')}
                                {canAddDomains && (
                                    <Button
                                        cls={b('field-action', { type: 'add-domain' })}
                                        type="link"
                                        theme="clear"
                                        size="xs"
                                        url="/portal/services/webmaster#add-domain"
                                    >
                                        <Icon glyph="yes">
                                            <CircledPlusIcon />
                                        </Icon>
                                    </Button>
                                )}
                            </div>
                        )}
                    </div>
                    <div className={b('field', { type: 'users' })}>
                        <label className={b('label')}>
                            {i18n('organization_profile.technical_details.users')}
                        </label>
                        <div className={b('value')}>
                            {org.user_count}
                        </div>
                    </div>
                    <div className={b('field', { type: 'departments' })}>
                        <label className={b('label')}>
                            {i18n('organization_profile.technical_details.departments')}
                        </label>
                        <div className={b('value')}>
                            {org.department_count}
                        </div>
                    </div>
                    <div className={b('field', { type: 'groups' })}>
                        <label className={b('label')}>
                            {i18n('organization_profile.technical_details.groups')}
                        </label>
                        <div className={b('value')}>
                            {org.group_count}
                        </div>
                    </div>
                    <div className={b('field', { type: 'admins' })}>
                        <label className={b('label')}>
                            {i18n('organization_profile.technical_details.admins')}
                        </label>
                        <div className={b('value')}>
                            {org.admin_count}
                        </div>
                    </div>
                    {isAdmin() && isPartnerOrganization() && (
                        <div className={b('field', { type: 'partner-id' })}>
                            <label className={b('label')}>
                                {i18n('organization_profile.technical_details.partner_id')}
                            </label>
                            <div className={b('value')}>
                                {org.partner_id || '—'}
                            </div>
                        </div>
                    )}
                    {isAdmin() && org.admin_count < 2 && (
                        <div className={b('tip', { type: 'admins' })}>
                            {i18n('organization_profile.technical_details.warning.too_few_admins')}
                        </div>
                    )}
                    {isAdmin() && hasOwnedDomains() && (
                        <div
                            className={b('tip', { type: 'ad-connector' })}
                            dangerouslySetInnerHTML={{
                                __html: i18n('organization_profile.ad_connector_message'),
                            }}
                        />
                    )}
                    {hasPermission('edit_organization') && (
                        <div className={b('controls')}>
                            <RemoveOrgControl
                                cls={b('button', { type: 'remove-org' })}
                            />
                        </div>
                    )}
                </div>
            </div>
        );
    }
}

export default OrgProfile;
