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

const actions = require('../actions');
const { removeTier } = require('../utils');
const buttons = require('./buttons');

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

        return {
            activeSkill,
            game,
            animating,
        };
    },

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

        function setGameSkillInfo(info) {
            dispatch(actions.setGameSkillInfo(info));
        }

        return { setActiveSkill, setGameSkillInfo };
    }
);


function Skill(props) {
    const {
        animating,
        construct,
        game,
        i,
        activeSkill,
        setActiveSkill,
        setGameSkillInfo,
    } = props;

    if (!game) return false;

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

    function hoverInfo(e, info) {
        e.stopPropagation();
        if (animating) return false;
        return setGameSkillInfo(info);
    }
    if (!s || !game) {
        return (
            <button
                disabled='true'
                class='construct-skill-btn disabled'>&nbsp;
            </button>
        );
    }

    // const skillChosen = game.stack.some(stack => stack.source_construct_id === construct.id);
    const targeting = game.stack.some(stack => stack.source_construct_id === construct.id && stack.skill === s.skill);

    // if (skillChosen && !targeting) {
    //     return false;
    // }
    const cdText = construct.skills[i].cd > 0
        ? `${s.cd}T`
        : '';

    const highlight = activeSkill
        ? activeSkill.constructId === construct.id && activeSkill.skill === s.skill
        : false;

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

    const border = buttons[removeTier(s.skill)] ? buttons[removeTier(s.skill)]() : '';

    return (
        <button
            disabled={cdText || s.disabled || ko}
            class={`${(targeting || highlight) ? 'active' : ''} ${border}`}
            onMouseOver={e => hoverInfo(e, { skill: s.skill, constructId: construct.id })}
            onMouseOut={e => hoverInfo(e, null)}
            type="submit"
            onClick={onClick}>
            <span>{s.skill} <br /> {cdText}</span>
        </button>
    );
}

module.exports = addState(Skill);
