import React from 'react';
import { Button, TextInput } from 'lego-on-react';
import StoreMixin from 'lib/StoreMixin';
import { i18n, formatDate } from 'lib/i18n';
import SubscriptionStore from 'stores/Subscription';
import SubscriptionActions from 'actions/Subscription';

import Form from 'ui/Form';

import './activate.css';

const Activate = React.createClass({

    mixins: [StoreMixin],

    getStoreState() {
        const { promoCode, statusDetails } = this.props;
        const activatedPromoCode = SubscriptionStore.getAvailablePromoCodes()[0];

        return {
            activatedPromoCode,
            promoCode: promoCode || '',
            isFormHidden: Boolean(activatedPromoCode && statusDetails),
            ready: Boolean(promoCode),
        };
    },

    componentDidMount() {
        this.subscribe(SubscriptionStore);

        if (this.props.autoFocus) {
            this.input.focus();
        }
    },

    _initialize(input) {
        this.input = input;
    },

    _handleSubmit(event) {
        const { promoCode } = this.state;

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

        this.setState({ ready: false });

        const data = { id: promoCode };

        return SubscriptionActions.activatePromoCode(data)
            .then(response => {
                if (response && response.errors) {
                    this.setState({
                        errors: response.errors,
                    });

                    return;
                }

                if (response && response.promocode) {
                    this.setState({
                        activatedPromoCode: response.promocode,
                        isFormHidden: this.props.statusDetails,
                    });
                }

                this.setState({ ready: true });
            })
            .catch(() => {
                this.setState({
                    errors: {
                        _common: i18n('common.status.failed'),
                    },
                    ready: true,
                });
            });
    },

    _handleInput(text) {
        this.setState({
            ready: Boolean(text),
            errors: null,
            promoCode: text,
        });
    },

    _handleSubmitInput(event) {
        if (event.keyCode === 13) {
            this._handleSubmit(event);
        }
    },

    _handleAddPromoCode() {
        const nextValue = !this.state.isFormHidden;

        this.setState({ isFormHidden: nextValue });

        if (!nextValue) {
            this.input.focus();
        }
    },

    render() {
        const { promoCode, ready, activatedPromoCode, isFormHidden } = this.state;
        let { errors } = this.state;
        let statusBlock;

        if (errors) {
            errors = errors.toJS ? errors.toJS() : errors;
        } else {
            errors = {};
        }

        if (this.props.statusDetails && activatedPromoCode) {
            const statusContent = {
                title: i18n('subscription.promocode.status_details', {
                    name: activatedPromoCode.id,
                }),
                details: i18n('subscription.promocode.expires', {
                    date: formatDate(activatedPromoCode.expires),
                }),
            };

            statusBlock = (
                <div className="promocode-status">
                    <div className="promocode-status__title">
                        {statusContent.title}
                    </div>
                    <div className="promocode-status__details">
                        {statusContent.details}
                    </div>
                    <div className="promocode-status__options">
                        <span className="link" onClick={this._handleAddPromoCode}>
                            {i18n('subscription.promocode.add_another')}
                        </span>
                    </div>
                </div>
            );
        }

        const className = [
            'promocode-activation-form form',
            isFormHidden ? 'promocode-activation-form_form-hidden' : null,
        ].filter(Boolean).join(' ');

        // заменяем форму обычным дивом, чтобы эту форму можно было
        // вкладывать внутрь других форм
        return (
            <div className={className}>
                <div className="form__item">
                    <div className="form__label">
                        <span>{i18n('subscription.promocode.form.label')}</span>
                    </div>
                    <div className="form__value-container">
                        <div className="form__value">
                            <TextInput
                                size="m"
                                autoComplete={false}
                                theme="normal"
                                view="default"
                                tone="default"
                                hasClear
                                ref={this._initialize}
                                onKeyDown={this._handleSubmitInput}
                                onChange={this._handleInput}
                                text={promoCode}
                            />
                            <Button
                                text={i18n('common.action.apply')}
                                theme="action"
                                size="m"
                                onClick={this._handleSubmit}
                                disabled={!ready}
                            />
                        </div>
                        <Form.Error value={errors.promoCode || errors._common} />
                    </div>
                </div>
                {statusBlock}
            </div>
        );
    },

});

export default Activate;
