import PropTypes from 'prop-types';
import React from 'react';
import { block } from 'bem-cn';
import StoreMixin from 'lib/StoreMixin';
import Url from 'lib/Url';
import { i18n } from 'lib/i18n';

import ConfigStore from 'stores/Config';
import SettingsStore from 'stores/Settings';
import AuthStore from 'stores/Auth';
import Metrika from 'lib/metrika';

import CommonHeader from 'ui/Header';
import OrgSwitch from 'components/OrgSwitch';
import HeaderUser from 'components/HeaderUser';
import HeaderNavigation from 'components/Navigation/Header';
import Search from 'components/Search';

import './index.css';

const bHeader = block('header');

const headerConfig = {
    appMenu: {
        onMenuButtonClick: () => Metrika.send('Шапка', 'Клик в бургер'),
    },
    logo: {
        key: 'related_services.yandex',
        onClick: () => Metrika.send('Шапка', 'Клик в логотип Яндекса'),
    },
    title: {
        key: 'related_services.connect',
        url: () => Url.getPath('home'),
    },
};

const Header = React.createClass({

    mixins: [StoreMixin],

    getStoreState() {
        let { services } = window.ya.connect.initial;
        const isStaffEnabled =
            SettingsStore.isEnabled('shared_contacts') &&
            AuthStore.isServiceEnabled('staff');

        // В случае ошибки в services лежит струкрутра {code: '<error-code>', message: '<error-message>'}
        // @see DIR-10404
        if (!Array.isArray(services)) {
            services = [];
        }

        return {
            services: (services || []).filter(({ enabled }) => enabled),
            logo: SettingsStore.getLogoUrl(),
            isSearchEnabled:
                this.props.searchEnabled &&
                !AuthStore.isIncompleteOrganization() &&
                (AuthStore.getViewMode() === 'admin' || isStaffEnabled),
        };
    },

    componentWillMount() {
        this._update();
    },

    componentDidMount() {
        this.subscribe(SettingsStore);
    },

    componentWillUpdate(nextProps, nextState) {
        this._update(nextState);
    },

    _update(state) {
        state = state || this.state;

        headerConfig.appMenu.services = state.services;

        ['logo', 'title'].forEach(item => {
            headerConfig[item].image = {
                src: state[item] || Url.build(ConfigStore.get('ui.logo'), {
                    text: i18n(headerConfig[item].key),
                }),
            };
        });
    },

    _handleSuggestSelect(payload) {
        Metrika.send('Шапка', 'Клик в элемент в саджесте');
        Url.open(payload.item.getUrl());
    },

    render() {
        const { orgSwitchEnabled } = this.props;
        const component = {};

        if (this.state.isSearchEnabled) {
            component.search = (
                <div className={bHeader('search')}>
                    <Search onSelect={this._handleSuggestSelect} width="available" />
                </div>
            );
        }

        if (orgSwitchEnabled) {
            component.OrgSwitch = <OrgSwitch />;
        }

        if (AuthStore.getViewMode() === 'staff') {
            component.HeaderNavigation = (
                <div className={bHeader('navigation')}>
                    <HeaderNavigation />
                </div>
            );
        }

        return (
            <CommonHeader {...headerConfig}>
                {component.OrgSwitch}
                {component.HeaderNavigation}
                <div className={bHeader('options-container', { navigation: Boolean(component.HeaderNavigation) })}>
                    {component.search}
                    <HeaderUser />
                </div>
            </CommonHeader>
        );
    },
});

Header.propTypes = {
    searchEnabled: PropTypes.bool,
    orgSwitchEnabled: PropTypes.bool,
};

Header.defaultProps = {
    searchEnabled: true,
    orgSwitchEnabled: true,
};

export default Header;
