import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import { Button, TextInput } from 'lego-on-react';
import { i18n } from 'lib/i18n';
import Url from 'lib/Url';
import Metrika from 'lib/metrika';

import Form from 'ui/Form';
import { Ruble as RubleIcon } from 'components/Icon';
import FormMixin from 'lib/FormMixin';
import StoreMixin from 'lib/StoreMixin';

import paymentValidator from 'validation/payment';
import SubscriptionActions from 'actions/Subscription';
import SubscriptionStore from 'stores/Subscription';
import filterInput from './filterInput';

import './index.css';

function getDefaultAmount() {
    const balance = SubscriptionStore.getBalance();

    return balance < 0 ? String(-balance) : '';
}

const MakePayment = React.createClass({

    mixins: [FormMixin, StoreMixin],

    getStoreState() {
        return {
            defaultAmount: getDefaultAmount(),
            hasContract: SubscriptionStore.hasContract(),
            errors: paymentValidator.getErrors(),
        };
    },

    componentDidMount() {
        this.subscribe([SubscriptionStore]);

        if (this.refs.amount) {
            this.refs.amount.focus();
        }
    },

    _handleFail(message) {
        this._setError(message || i18n('common.status.failed'));
    },

    _handleSubmit(data) {
        const { onSubmit } = this.props;

        if (!this.state.hasContract) {
            return SubscriptionActions.toAgreement('balance');
        }

        if (this._use(paymentValidator, filterInput)._validate(data)) {
            Metrika.send('Текущий баланс', 'Пополнить');

            return SubscriptionActions.makePayment(data)
                .then(response => {
                    if (response && response.errors) {
                        return this._handleFail(response.errors.get('_common'));
                    }

                    const paymentUrl = _.get(response, 'subscription.payment.url');

                    if (paymentUrl) {
                        Url.open(paymentUrl);
                        if (onSubmit) {
                            onSubmit();
                        }
                    } else {
                        this._handleFail();
                    }
                })
                .catch(() => {
                    this._handleFail();
                });
        }
    },

    _renderPopup() {
        const errors = this.state.errors.toJS();

        return (
            <Form
                className="balance__payment-form_popup form"
                onSubmit={this._handleSubmit}
                autoComplete={false}
            >

                <Form.Item
                    label={i18n('subscription.balance.payment.message')}
                    errors={errors.amount}
                >
                    <TextInput
                        size="m"
                        name="amount"
                        autoComplete={false}
                        theme="normal"
                        view="default"
                        tone="default"
                        hasClear
                        placeholder={i18n('subscription.balance.payment.amount.placeholder.RUB')}
                        ref="amount"
                        onChange={this._onInputChange}
                        text={this.state.defaultAmount}
                    />
                </Form.Item>
                <Form.Error value={errors._common} mod="standalone" />

                <Form.Buttons mod="right-aligned">
                    <Button
                        text={i18n('subscription.balance.payment.go_to_payment')}
                        theme="action"
                        size="m"
                        type="submit"
                    />
                </Form.Buttons>
            </Form>
        );
    },

    _onInputChange(text) {
        this.setState({ defaultAmount: text });
    },

    render() {
        const errors = this.state.errors.toJS();

        if (this.props.mod === 'popup') {
            return this._renderPopup();
        }

        return (
            <Form
                className="balance__payment-form form"
                onSubmit={this._handleSubmit}
                autoComplete={false}
            >
                <div className="form__value">
                    <div className="form__input">
                        <TextInput
                            size="m"
                            name="amount"
                            autoComplete={false}
                            theme="normal"
                            view="default"
                            tone="default"
                            hasClear
                            placeholder={i18n('balance.payment_amount')}
                            ref="amount"
                            onChange={this._onInputChange}
                            iconRight={<RubleIcon width="14" height="14" />}
                            text={this.state.defaultAmount}
                        />
                        <Form.Error value={errors.amount} mod="standalone" />
                    </div>
                    <Button
                        text={i18n('subscription.balance.make_payment')}
                        theme="action"
                        size="m"
                        type="submit"
                    />
                </div>
                <Form.Error value={errors._common} mod="standalone" />

            </Form>
        );
    },
});

MakePayment.propTypes = {
    mod: PropTypes.oneOf(['inline', 'popup']),
};

MakePayment.defaultProps = {
    mod: 'inline',
};

export default MakePayment;
