import _ from 'lodash';
import React from 'react';
import Url from 'lib/Url';
import { i18n } from 'lib/i18n';
import RestoreActions from 'actions/Restore';

import Form from 'lego-ui/Form';
import Input from 'lego-ui/Input';
import TextArea from 'lego-ui/TextArea';
import Checkbox from 'lego-ui/Checkbox';
import Button from 'lego-ui/Button';

import './index.css';

const VALID_DOMAIN_PATTERN = /^\S+\.[^\s\.]+$/;
const OWNER_REQUEST_TIMEOUT = 750;

export default React.createClass({

    getInitialState() {
        return {
            adminsDisabled: false,
            usersDisabled: false,
            maillistsDisabled: false,
        };
    },

    _setMainFocus(element) {
        if (element) {
            element.focus();
        }
    },

    _toggleDisabled(key, value) {
        this.setState({ [`${key}Disabled`]: value });
    },

    _onDomainChange(event) {
        const domain = event.target.value;

        if (domain === this.state.domain) {
            return;
        }

        clearTimeout(this._ownerRequestTimeout);

        this.setState({
            domain,
            owner: null,
        });

        if (!VALID_DOMAIN_PATTERN.test(domain)) {
            return;
        }

        this._ownerRequestTimeout = setTimeout(() => {
            // получаем маскированный логин текущего владельца для подсказки
            RestoreActions.getCurrentOwner(domain)
                .then(data => {
                    let owner = _.get(data, 'current_owner.owner_login');

                    // если полученный маскированный логин состоит только
                    // из звёздочек перед @, такая подсказка ничего нового не скажет,
                    // поэтому такой вариант не показываем
                    if (owner && owner.split('@')[0] === '***') {
                        owner = null;
                    }

                    this.setState({
                        domain,
                        owner,
                    });
                });
        }, OWNER_REQUEST_TIMEOUT);
    },

    render() {
        const { props, state } = this;

        // пустая подсказка заполняется неразрывным пробелом,
        // чтобы при появлении текста не было скачка контента
        let domainTipContent = '\u00a0';

        if (state.domain && state.owner) {
            domainTipContent = i18n('restore.domain.owner_tip', {
                domain: state.domain,
                owner: state.owner,
            });
        }

        return (
            <div className="control-questions">
                <h1 className="control-questions__title">
                    {i18n('restore.control_questions.title')}
                </h1>
                <Form onSubmit={props.onSubmit} className="control-questions__form">
                    <div className="control-question">
                        <div>
                            <label className="control-question__label" htmlFor="domain">
                                {i18n('restore.domain.title')}
                            </label>
                        </div>
                        <div>
                            <Input
                                id="domain"
                                name="domain"
                                defaultValue={Url.getQueryParam('domain')}
                                width="available"
                                ref={this._setMainFocus}
                                onInput={this._onDomainChange}
                                onKeyDown={this._onDomainChange}
                                onBlur={this._onDomainChange}
                            />
                        </div>
                        <div
                            className="control-question__tip"
                            dangerouslySetInnerHTML={{ __html: domainTipContent }}
                        />
                    </div>
                    <div className="control-questions__description">
                        {i18n('restore.control_questions.description')}
                    </div>
                    <div className="control-question">
                        <div>
                            <label className="control-question__label" htmlFor="admins">
                                {i18n('restore.admins.title')}
                            </label>
                        </div>
                        <div className={state.adminsDisabled ? 'hidden' : null}>
                            <TextArea
                                id="admins"
                                name="admins"
                                width="available"
                                placeholder={i18n('restore.admins.tip')}
                                disabled={state.adminsDisabled}
                            />
                        </div>
                        <div>
                            <Checkbox
                                name="forgot_admins"
                                text={i18n('restore.admins.forgot_admins')}
                                defaultChecked={state.adminsDisabled}
                                onChange={event => {
                                    this._toggleDisabled('admins', event.target.checked);
                                }}
                            />
                        </div>
                    </div>
                    <div className="control-question">
                        <div>
                            <Checkbox
                                text={i18n('restore.users.available')}
                                defaultChecked={!state.usersDisabled}
                                onChange={event => {
                                    this._toggleDisabled('users', !event.target.checked);
                                }}
                            />
                            <input
                                type="hidden"
                                name="no_users"
                                value={state.usersDisabled}
                            />
                        </div>
                        <div className={state.usersDisabled ? 'hidden' : null}>
                            <TextArea
                                id="users"
                                name="users"
                                width="available"
                                placeholder={i18n('restore.users.tip')}
                                disabled={state.usersDisabled}
                            />
                        </div>
                    </div>
                    <div className="control-question">
                        <div>
                            <Checkbox
                                text={i18n('restore.maillists.available')}
                                defaultChecked={!state.maillistsDisabled}
                                onChange={event => {
                                    this._toggleDisabled('maillists', !event.target.checked);
                                }}
                            />
                            <input
                                type="hidden"
                                name="no_maillists"
                                value={state.maillistsDisabled}
                            />
                        </div>
                        <div className={state.maillistsDisabled ? 'hidden' : null}>
                            <TextArea
                                id="maillists"
                                name="maillists"
                                width="available"
                                placeholder={i18n('restore.maillists.tip')}
                                disabled={state.maillistsDisabled}
                            />
                        </div>
                    </div>
                    <div className="control-questions__buttons">
                        <Button
                            view="action"
                            text={i18n('common.action.done')}
                            type="submit"
                        />
                    </div>
                </Form>
            </div>
        );
    },

});
