const { connect } = require('preact-redux');
const preact = require('preact');
const { Elements, injectStripe } = require('react-stripe-elements');

const { saw } = require('./shapes');
const { postData } = require('./../utils');

function pingColour(ping) {
    if (ping < 100) return 'forestgreen';
    if (ping < 200) return 'yellow';
    return 'red';
}

function BitsBtn(args) {
    const {
        stripe,
        account,
    } = args;
    function subscribeClick(e) {
        stripe.redirectToCheckout({
            items: [{plan: 'plan_FGmRwawcOJJ7Nv', quantity: 1}],
            successUrl: 'http://localhost/api/payments/success',
            cancelUrl: 'http://localhost/api/payments/cancel',
            clientReferenceId: account.id
        });
    }

    function bitsClick(e) {
        stripe.redirectToCheckout({
            items: [{sku: 'sku_FHUfNEhWQaVDaT', quantity: 1}],
            successUrl: 'http://localhost/payments/success',
            cancelUrl: 'http://localhost/payments/cancel',
            clientReferenceId: account.id
        });
    }

    const subscription = account.subscribed
        ? <h3 class="account-header">Subscribed</h3>
        : <button
            onClick={subscribeClick}
            class="stripe-btn"
            role="link">
            Subscribe
        </button>;

    return (
        <div>
            <div id="error-message"></div>
            {subscription}
            <button
                onClick={bitsClick}
                class="stripe-btn"
                role="link">
                Get Credits
            </button>

        </div>
    );
}

const StripeBitsBtn = injectStripe(BitsBtn);

const addState = connect(
    function receiveState(state) {
        const {
            account,
            ping,
        } = state;

        function logout() {
            postData('/logout').then(() => window.location.reload(true));
        }

        return {
            account,
            ping,
            logout,
        };
    },
);


function AccountStatus(args) {
    const {
        account,
        ping,
        logout,
    } = args;

    if (!account) return null;

    return (
        <div class="account">
            <div class="account-status">
                <h2 class="account-header">{account.name}</h2>
                {saw(pingColour(ping))}
                <div class="ping-text">{ping}ms</div>
            </div>
            <h3 class="account-header">{`¤${account.balance}`}</h3>
            <Elements>
                <StripeBitsBtn account={account} />
            </Elements>
            <button onClick={() => logout()}>Logout</button>
        </div>
    );
}

module.exports = addState(AccountStatus);
