const preact = require('preact');
const { connect } = require('preact-redux');

const actions = require('../actions');

const addState = connect(
    function receiveState(state) {
        const {
            ws,
            instance,
            tutorial,
        } = state;

        function sendAbandon() {
            return ws.sendInstanceAbandon(instance.id);
        }

        return {
            instance,
            tutorial,
            sendAbandon,
        };
    },
    function receiveDispatch(dispatch) {
        function leave(tutorial) {
            dispatch(actions.setNav('play'));
            dispatch(actions.setGame(null));
            dispatch(actions.setInstance(null));
            dispatch(actions.setVboxSelected({ storeSelect: [], stashSelect: [] }));
            dispatch(actions.setInfo(null));
            dispatch(actions.setItemUnequip([]));
            if (tutorial) dispatch(actions.setTutorial(1));
        }

        return { leave };
    }
);

function InstanceTopBtns(args) {
    const {
        instance,

        leave,
        sendAbandon,
        tutorial,
    } = args;

    const finished = instance && instance.phase === 'Finished';
    const { abandonState } = this.state;

    const abandonStateTrue = e => {
        e.stopPropagation();
        this.setState({ abandonState: true });
        setTimeout(() => this.setState({ abandonState: false }), 2000);
    };

    const abandonClasses = `abandon ${abandonState ? 'confirming' : ''}`;
    const abandonText = abandonState ? 'Confirm' : 'Abandon';
    const abandonAction = abandonState ? sendAbandon : abandonStateTrue;

    const abandonBtn = <button class={abandonClasses} disabled={finished} onClick={abandonAction}>{abandonText}</button>;
    const leaveBtn = <button class='abandon confirming' onClick={() => leave(tutorial)}>Leave</button>;

    return (
        <div class="instance-ctrl-btns">
            {finished ? leaveBtn : abandonBtn}
        </div>
    );
}

module.exports = addState(InstanceTopBtns);
