import React from 'react';
import { Button, TextInput } from 'lego-on-react';
import { Permissions } from 'constants/Common';
import StoreMixin from 'lib/StoreMixin';
import { i18n, formatDate } from 'lib/i18n';

import SubscriptionActions from 'actions/Subscription';
import SubscriptionStore from 'stores/Subscription';
import PermissionStore from 'stores/Permissions';

function getDefaultPromoCode() {
    return location.hash.substring(1);
}

const PromoCodes = React.createClass({

    mixins: [StoreMixin],

    getStoreState() {
        const items = SubscriptionStore.getAvailablePromoCodes();
        const promoCode = getDefaultPromoCode();

        return {
            items,
            isAvailable: PermissionStore.contains(Permissions.ACTIVATE_PROMOCODE),
            inputValue: promoCode || '',
            isFormOpen: !items || !items.length,
            isInputEmpty: !promoCode,
        };
    },

    componentDidMount() {
        this.subscribe([SubscriptionStore, PermissionStore]);
    },

    _initializeInput(element) {
        this.input = element;

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

    _handleInput(text) {
        this.setState({
            isInputEmpty: !text,
            errors: null,
            inputValue: text,
        });
    },

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

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

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

        const data = { id: promoCode };

        return SubscriptionActions.activatePromoCode(data)
            .then(response => {
                if (response && response.errors) {
                    this.setState({
                        errors: response.errors,
                        isFormOpen: true,
                    });
                }
            })
            .catch(() => {
                this.setState({
                    errors: {
                        _common: i18n('common.status.failed'),
                    },
                    isFormOpen: true,
                });
            });
    },

    _toggleForm() {
        this.setState({
            isFormOpen: !this.state.isFormOpen,
            isInputEmpty: !this.input || !this.state.inputValue,
            errors: null,
        });
    },

    _renderList() {
        const { items } = this.state;

        if (!items || !items.length) {
            return null;
        }

        return (
            <div className="balance__promocode-list">
                {items.map(this._renderItem)}
            </div>
        );
    },

    _renderItem(item, index) {
        const base = 'balance__promocode-list-item';
        const title = i18n('balance.promocode.title', {
            promocode_name: item.name || item.id,
        });
        const details = i18n('balance.promocode.expiration', {
            expiration_date: formatDate(item.expires),
        });

        return (
            <div className={base} key={index}>
                <div className={`${base}__title`}>
                    <span
                        className={`${base}__name`}
                        dangerouslySetInnerHTML={{ __html: title }}
                    />
                    <span className="link" onClick={this._toggleForm}>
                        {i18n('balance.promocode.change')}
                    </span>
                </div>
                <div className={`${base}__description`}>{item.description}</div>
                <div className={`${base}__details`}>{details}</div>
            </div>
        );
    },

    _renderForm() {
        const base = 'balance__promocode-form';
        const { items, inputValue, isInputEmpty } = this.state;
        let { errors } = this.state;
        let cancelButton;

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

        if (items && items.length) {
            cancelButton = (
                <span className="link" onClick={this._toggleForm}>
                    {i18n('common.action.cancel')}
                </span>
            );
        }

        return (
            <div className={base}>
                <h3 className={`${base}__title`}>
                    {i18n('balance.promocode.subtitle')}
                </h3>
                <div className={`${base}__value`}>
                    <TextInput
                        size="m"
                        autoComplete={false}
                        theme="normal"
                        view="default"
                        tone="default"
                        placeholder={i18n('balance.promocode.placeholder')}
                        hasClear
                        ref={this._initializeInput}
                        onKeyDown={this._handleSubmitInput}
                        onChange={this._handleInput}
                        text={inputValue}
                    />
                    <Button
                        text={i18n('common.action.apply')}
                        size="m"
                        theme="action"
                        onClick={this._handleSubmit}
                        disabled={isInputEmpty}
                    />
                    {cancelButton}
                </div>
                <div className={`${base}__error`}>
                    {errors.promoCode || errors._common}
                </div>
            </div>
        );
    },

    render() {
        if (!this.state.isAvailable) {
            return null;
        }

        return (
            <div className="balance__promocodes">
                {this.state.isFormOpen ? this._renderForm() : this._renderList()}
            </div>
        );
    },

});

export default PromoCodes;
