const preact = require('preact');
const { Component } = require('preact');
const { connect } = require('preact-redux');
const linkState = require('linkstate').default;

const { postData, errorToast } = require('./../../client/src/utils');
const actions = require('./actions');

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

        return {
            user,
        };
    },
    function receiveDispatch(dispatch) {
        function setUser(user) {
            dispatch(actions.setUser(user));
        }

        function setMsg(msg) {
            dispatch(actions.setMsg(msg));
        }

        return {
            setUser,
            setMsg,
        };
    }
);

function AcpUser(args) {
    const {
        user,
        setUser,
        setMsg,
    } = args;

    const {
        credits,
    } = this.state;

    if (!user) return false;

    const reset = () => {
        setMsg(null);
        this.setState({ credits: null });
    };

    const addCredits = () => {
        reset();
        postData('/acp/user/credits', { id: user.id, credits })
            .then(res => res.json())
            .then(data => {
                if (data.error) return setMsg(data.error);
                return setUser(data);
            })
            .catch(error => setMsg(error));
    };

    return (
        <div class="user">
            <dl>
                <h1>{user.name}</h1>
                <dt>Id</dt>
                <dd>{user.id}</dd>
                <dt>Credits</dt>
                <dd>{user.balance}</dd>
                <dt>Subscribed</dt>
                <dd>{user.subscribed.toString()}</dd>
            </dl>
            <div>
                <label for="current">Add Credits:</label>
                <input
                    class="login-input"
                    type="number"
                    name="credits"
                    value={credits}
                    onInput={linkState(this, 'credits')}
                    placeholder="credits"
                />
                <button
                    onClick={addCredits}>
                    Add Credits
                </button>
            </div>
            <div>
                <h2>Constructs</h2>
            </div>
        </div>
    );
}

module.exports = addState(AcpUser);
