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

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

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

        return {
            activeSkill,
            game,
        };
    },

    function receiveDispatch(dispatch) {
        function setActiveSkill(crypId, skill) {
            dispatch(actions.setActiveSkill(crypId, skill));
        }

        return { setActiveSkill };
    }
);


function Skill(props) {
    const {
        cryp,
        game,
        i,
        mobile,
        activeSkill,
        setActiveSkill,
    } = props;

    const s = cryp.skills[i];
    const ko = cryp.green_life.value === 0 ? 'ko' : '';

    if (!s) {
        return (
            <button
                disabled='true'
                className='cryp-skill-btn disabled'>
            </button>
        );
    }

    const side = mobile
        ? 'top'
        : '';

    const cdText = cryp.skills[i].cd > 0
        ? `- ${s.cd}T`
        : '';

    const highlight = activeSkill
        ? activeSkill.crypId === cryp.id && activeSkill.skill === s.skill
        : false;

    function onClick(e) {
        e.stopPropagation();
        return setActiveSkill(cryp.id, s.skill);
    }

    const targeting = game.stack.some(stack => stack.source_cryp_id === cryp.id && stack.skill === s.skill);

    return (
        <button
            disabled={!!cdText || ko}
            className={`cryp-skill-btn ${side} ${(targeting || highlight) ? 'active' : ''}`}
            type="submit"
            onClick={onClick}>
            {s.skill} {cdText}
        </button>
    );
}

module.exports = addState(Skill);
