/* eslint no-console: "off" */
import React from 'react';

import _ from 'lodash';

import { Button, TextInput, Link } from 'lego-on-react';
import Url from 'lib/Url';

import ModalBox from 'components/ModalBox';
import ModalActions from 'actions/Modal';
import AuthStore from 'stores/Auth';

import Header from 'components/Header';

import './index.css';

const defaultResourceId = 'mail';

const BindWidgetFakePage = React.createClass({

    getInitialState() {
        const userId = AuthStore.getUserId();

        return {
            resourceId: defaultResourceId,
            fields: {
                resourceId: Math.floor(1e6 * Math.random()).toString(),
                service: 'metrika',
                roleName: 'role',
                'rolesId[1]': userId,
            },
            rolesCount: 1,
            promoWidth: 0,
            promoHeight: 0,
            isPromoAvailable: true,
        };
    },

    componentDidMount() {
        window.addEventListener('message', this._onMessage);
    },

    _onMessage(windowEvent) {
        const data = windowEvent.data;

        console.log('_onMessage', data);

        if (!data) {
            return;
        }

        if (data.message === 'connect_bind_promo_size' && data.size) {
            this.setState({
                promoHeight: data.size.height,
                promoWidth: data.size.width,
            });
        }

        if (data.message === 'connect_bind_promo_confirm') {
            this._openBindWidget();
        }

        if (data.message === 'connect_bind_promo_unavailable') {
            this.setState({
                isPromoAvailable: false,
            });
        }
    },

    _openBindWidget(event) {
        if (event) {
            event.preventDefault();
        }

        const { name } = this.props;
        const { fields: { resourceId, service, roleName }, rolesCount } = this.state;
        const relations = [];

        for (let i = 1; i <= rolesCount; i++) {
            const rolesId = this.state.fields[`rolesId[${i}]`];

            if (rolesId) {
                relations.push({
                    object_id: Number(rolesId),
                    object_type: 'user',
                    name: roleName,
                });
            }
        }

        console.log('======================= WidgetWrapper props ======================');
        console.log({
            name,
            resourceId,
            service,
            relations,
            onMessage: this._onMessage,
        });

        ModalActions.open({
            component: WidgetWrapper,
            props: {
                name,
                resourceId,
                service,
                relations,
                onMessage: this._onMessage,
                onCancel: () => ModalActions.close(),
            },
        });
    },

    _onInputChange(name, value) {
        this.setState({
            fields: _.assign(this.state.fields, { [name]: value }),
        });
    },

    _onSampleClick(value) {
        this.setState({
            fields: _.assign(this.state.fields, { service: value }),
        });
    },

    _onRandomClick() {
        this.setState({
            fields: _.assign(this.state.fields, { resourceId: Math.floor(1e6 * Math.random()).toString() }),
        });
    },

    _setFormRef(form) {
        this._form = form;
    },

    _getDescription(name) {
        if (name === 'resourceId') {
            return 'ID ресурса';
        }

        if (name === 'service') {
            return 'ID сервиса';
        }

        if (name === 'roleName') {
            return 'Название роли';
        }

        return 'ID пользователя';
    },

    _renderField(name) {
        const text = this.state.fields[name];

        return (
            <div className="bind-widget-fake-page__field" key={`field_${name}`}>
                <span className="bind-widget-fake-page__field-description">
                    {this._getDescription(name)}
                </span>
                <div className="bind-widget-fake-page__field-input">
                    <TextInput
                        cls="bind-widget-fake-page__field-input"
                        name={name}
                        theme="normal"
                        size="s"
                        text={text}
                        onChange={this._onInputChange.bind(this, name)}
                    />
                    {name === 'service' && (
                        <div className="bind-widget-fake-page__samples">
                            {['metrika', 'yandexsprav', 'direct', 'forms'].map(slug => (
                                <Link
                                    cls="bind-widget-fake-page__sample"
                                    theme="pseudo"
                                    type="pseudo"
                                    key={slug}
                                    onClick={this._onSampleClick.bind(this, slug)}
                                >
                                    {slug}
                                </Link>
                            ))}
                        </div>
                    )}
                    {name === 'resourceId' && (
                        <div className="bind-widget-fake-page__random">
                            <Link
                                cls="bind-widget-fake-page__sample"
                                theme="pseudo"
                                type="pseudo"
                                onClick={this._onRandomClick}
                            >
                                Мне повезет
                            </Link>
                        </div>
                    )}
                </div>
            </div>
        );
    },

    _renderFields() {
        const { rolesCount } = this.state;

        const fields = [
            this._renderField('resourceId'),
            this._renderField('service'),
            this._renderField('roleName'),
        ];

        for (let i = 1; i <= rolesCount; i++) {
            fields.push(this._renderField(`rolesId[${i}]`));
        }

        return fields;
    },

    _addRoleId() {
        this.setState({
            rolesCount: this.state.rolesCount + 1,
        });
    },

    _sendDataForPromo(event) {
        if (event) {
            event.preventDefault();
        }

        const { fields: { resourceId, service, roleName }, rolesCount } = this.state;
        const relations = [];

        for (let i = 1; i <= rolesCount; i++) {
            const rolesId = this.state.fields[`rolesId[${i}]`];

            if (rolesId) {
                relations.push({
                    object_id: Number(rolesId),
                    object_type: 'user',
                    name: roleName,
                });
            }
        }

        if (this._promo && this._promo.contentWindow) {
            this._promo.contentWindow.postMessage({
                name: 'bind-promo',
                message: 'connect_resource_response',
                service_slug: service,
                resource_id: resourceId,
                relations,
            }, '*');
        }
    },

    _setPromoRef(component) {
        this._promo = component;
    },

    _onLayoutClick(val) {
        this.setState({
            width: val,
        });
    },

    _renderPromo() {
        const { isPromoAvailable, promoHeight, promoWidth } = this.state;

        if (!isPromoAvailable) {
            return null;
        }

        return (
            <div className={`bind-widget-fake-page__layout bind-widget-fake-page__layout_width_${this.state.width}`}>
                {promoWidth !== 0 && (
                    <div>
                        {[210, 300, 610, 740, 1000].map(val => (
                            <Link
                                cls="bind-widget-fake-page__layout-link"
                                theme="pseudo"
                                type="pseudo"
                                key={val}
                                onClick={this._onLayoutClick.bind(this, val)}
                            >
                                {val}
                            </Link>
                        ))}
                    </div>
                )}
                <iframe
                    className="bind-widget-fake-page__promo"
                    ref={this._setPromoRef}
                    frameBorder="0"
                    marginHeight="0"
                    marginWidth="0"
                    width={promoWidth}
                    height={promoHeight}
                    allowTransparency
                    name="bind-promo"
                    src={`/widget/bind-promo?lang=${Url.getQueryParam('lang')}`}
                />
            </div>

        );
    },

    render() {
        return (
            <div>
                <Header />
                <div className="bind-widget-fake-page">
                    <h1>
                        Пример страницы с виджетом связывания
                    </h1>

                    {this._renderPromo()}

                    <form
                        onSubmit={this._openBindWidget}
                        ref={this._setFormRef}
                        className="bind-widget-fake-page__content"
                    >

                        <div className="bind-widget-fake-page__fields">
                            {this._renderFields()}
                            <span
                                className="bind-widget-fake-page__pseudo-link"
                                onClick={this._addRoleId}
                            >

                                Добавить пользователя
                            </span>
                        </div>

                        <Button
                            theme="action"
                            view="default"
                            tone="default"
                            size="m"
                            type="submit"
                        >

                            Привязать ресурс
                        </Button>

                        <Button
                            cls="bind-widget-fake-page__promo-button"
                            theme="action"
                            view="default"
                            tone="default"
                            size="m"
                            onClick={this._sendDataForPromo}
                        >
                            Показать промо связывания
                        </Button>
                    </form>
                </div>

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

const WidgetWrapper = React.createClass({

    getInitialState() {
        return {
            height: 0,
            width: 0,
        };
    },

    componentDidMount() {
        window.addEventListener('message', this._onMessage);
    },

    componentWillUnmount() {
        window.removeEventListener('message', this._onMessage);
    },

    _onSubmit() {
        // noop
    },

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

    _onMessage({ data, source }) {
        const { relations, name: widgetName, service, resourceId } = this.props;
        const { message, size, name } = data;

        if (name !== widgetName) {
            return;
        }

        if (message === 'connect_resource_request') {
            console.log('======================= ping response ======================');
            console.log({
                name: widgetName,
                message: 'connect_resource_response',
                resource_id: resourceId,
                relations,
            });

            source.postMessage({
                name: widgetName,
                message: 'connect_resource_response',
                service_slug: service,
                resource_id: resourceId,
                relations,
            }, '*');
        } else if (message === 'connect_resource_bound') {
            this._onSubmit();
        } else if (message === 'connect_bind_widget_closed') {
            this._onCancel();
        }

        if (size) {
            this._setSize({
                height: Number(size.height),
                width: Number(size.width),
            });
        }

        this.props.onMessage(data);
    },

    _setSize({ height, width }) {
        this.setState({ height, width });
    },

    render() {
        const { name } = this.props;
        const { height, width } = this.state;

        return (
            <iframe
                frameBorder="0"
                marginHeight="0"
                marginWidth="0"
                width={width}
                height={height}
                allowTransparency
                name={name}
                src={`/widget/add-resource?lang=${Url.getQueryParam('lang')}`}
            />
        );
    },
});

export default BindWidgetFakePage;
