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

const preact = require('preact');
const toast = require('izitoast');

const actions = require('./../actions');
const StripeBtns = require('./stripe.buttons');

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

        function mtxBuy(mtx) {
            return ws.sendMtxBuy(mtx.variant);
        }

        return {
            account,
            shop,
            mtxBuy,
        };
    },

    function receiveDispatch(dispatch) {
        function setMtxActive(mtx) {
            dispatch(actions.setConstructRename(null));
            dispatch(actions.setMtxActive(mtx));
            return true;
        }

        return {
            setMtxActive,
        };
    }
);

function Inventory(args) {
    const {
        account,
        shop,
        setMtxActive,
        mtxBuy,
    } = args;

    if (!shop) return false;

    const useMtx = (item, i) => (
        <figure key={i} onClick={() => setMtxActive(item)} >
            <figcaption>{item}</figcaption>
            <button disabled={account.balance === 0}>¤1</button>
        </figure>
    );

    const availableMtx = (item, i) => (
        <figure key={i} onClick={() => mtxBuy(item)} >
            <figcaption>{item.variant}</figcaption>
            <button disabled={account.balance < item.credits}>¤{item.credits}</button>
        </figure>
    );

    return (
        <div class="inventory">
            <div>
                <h1>Shop</h1>
                <Elements>
                    <StripeBtns account={account} />
                </Elements>
                <div class='list'>
                    {shop.available.map(availableMtx)}
                </div>
            </div>
            <div>
                <h1 class="credits">¤ {account.balance}</h1>
                <div class='list'>
                    {shop.owned.map(useMtx)}
                </div>
            </div>
        </div>
    );
}

module.exports = addState(Inventory);
