const preact = require('preact');
const { connect } = require('preact-redux');
const range = require('lodash/range');
const countBy = require('lodash/countBy');
const without = require('lodash/without');

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

const addState = connect(
    function receiveState(state) {
        const {
            ws,
            instance,
            player,
            combiner,
            reclaiming,
            vboxSelected,
            itemInfo,
            itemUnequip,
            tutorial,
        } = state;

        function sendVboxDiscard() {
            return ws.sendVboxDiscard(instance.id);
        }

        function sendVboxAccept(group, index) {
            document.activeElement.blur();
            return ws.sendVboxAccept(instance.id, group, index);
        }

        function sendVboxCombine() {
            return ws.sendVboxCombine(instance.id, combiner);
        }

        function sendVboxReclaim(i) {
            return ws.sendVboxReclaim(instance.id, i);
        }

        function sendItemUnequip([constructId, item]) {
            return ws.sendVboxUnequip(instance.id, constructId, item);
        }

        return {
            combiner,
            instance,
            player,
            reclaiming,
            sendVboxAccept,
            sendVboxCombine,
            sendVboxDiscard,
            sendVboxReclaim,
            vboxSelected,
            itemInfo,
            itemUnequip,
            sendItemUnequip,
            tutorial,
        };
    },

    function receiveDispatch(dispatch) {
        function setCombiner(c) {
            return dispatch(actions.setCombiner(c));
        }

        function setReclaiming(v) {
            return dispatch(actions.setReclaiming(v));
        }

        function setInfo(item) {
            return dispatch(actions.setInfo(item));
        }

        function setVboxSelected(v) {
            return dispatch(actions.setVboxSelected(v));
        }

        function setItemEquip(v) {
            return dispatch(actions.setItemEquip(v));
        }

        return {
            setCombiner,
            setReclaiming,
            setInfo,
            setVboxSelected,
            setItemEquip,
        };
    }

);

class Vbox extends preact.Component {
    shouldComponentUpdate(newProps) {
        // Single variable props
        if (newProps.combiner !== this.props.combiner) return true;
        if (newProps.itemUnequip !== this.props.itemUnequip) return true;
        if (newProps.reclaiming !== this.props.reclaiming) return true;
        if (newProps.tutorial !== this.props.tutorial) return true;
        if (newProps.vboxSelected !== this.props.vboxSelected) return true;
        if (newProps.player !== this.props.player) return true;
        if (newProps.instance !== this.props.instance) return true;
        return false;
    }

    render(args) {
        const {
            // Changing state variables
            combiner,
            itemUnequip,
            player,
            reclaiming,
            tutorial,
            vboxSelected,
            instance,

            // Static
            itemInfo,
            // Function Calls
            sendItemUnequip,
            sendVboxAccept,
            sendVboxCombine,
            sendVboxDiscard,
            sendVboxReclaim,
            setVboxSelected,
            setItemEquip,
            setInfo,
            setCombiner,
            setReclaiming,
        } = args;

        if (!player) return false;
        const { vbox } = player;
        const vboxSelecting = vboxSelected.length;

        function combinerChange(newCombiner) {
            setCombiner(newCombiner);

            if (newCombiner.length === 1) {
                setItemEquip(newCombiner[0]);
            } else {
                setItemEquip(null);
            }

            return true;
        }

        //
        // VBOX
        //
        function vboxHover(e, v) {
            if (v) {
                e.stopPropagation();
                if (vboxSelected[0]) return true; // There is a base skill or spec selected in the vbox
                if (combiner.length !== 0) {
                    const base = combiner.find(c => !['Red', 'Blue', 'Green'].includes(vbox.bound[c]));
                    if (base || base === 0) return true;
                }
                setInfo(v);
            }
            return true;
        }

        function clearVboxSelected() {
            setVboxSelected([]);
        }

        function vboxBuySelected() {
            if (!vboxSelecting) return false;
            document.activeElement.blur();
            clearVboxSelected();
            sendVboxAccept(vboxSelected[0], vboxSelected[1]);
            return true;
        }

        function availableBtn(v, group, index) {
            if (!v) return <button disabled class='empty' key={(group * 10) + index} >&nbsp;</button>;
            const selected = vboxSelected[0] === group && vboxSelected[1] === index;

            // state not yet set in double click handler
            function onDblClick(e) {
                clearVboxSelected();
                sendVboxAccept(group, index);
                e.stopPropagation();
            }

            function onClick(e) {
                e.stopPropagation();
                setItemEquip(null);
                setCombiner([]);
                setInfo(vbox.free[group][index]);
                return setVboxSelected([group, index]);
            }

            const combinerItems = combiner.map(j => vbox.bound[j]);
            const combinerCount = countBy(combinerItems, co => co);

            const comboHighlight = combinerItems.length > 0 && itemInfo.combos.some(combo => {
                if (combo.components.includes(v)) {
                    return combinerItems.every(c => {
                        if (!combo.components.includes(c)) return false;
                        const comboCount = countBy(combo.components, co => co);
                        if (combinerCount[c] > comboCount[c]) return false;
                        if (c === v && combinerCount[c] + 1 > comboCount[c]) return false;
                        return true;
                    });
                } return false;
            }) ? 'combo-border' : '';

            const classes = `${v.toLowerCase()} ${selected ? 'highlight' : ''} ${comboHighlight}`;

            const vboxObject = shapes[v] ? shapes[v]() : v;
            const disabled = vbox.bits <= group;
            return (
                <label draggable='true'
                    onDragStart={ev => {
                        onClick(ev);
                        ev.dataTransfer.setData('text', '')
                    }}
                    key={group * 10 + index}
                    onDragEnd={clearVboxSelected}>
                    <button
                        class={classes}
                        disabled={disabled}
                        onMouseOver={e => vboxHover(e, v)}
                        onMouseDown={onClick}
                        onClick={e => e.stopPropagation()}
                        onDblClick={onDblClick}
                    > {vboxObject}
                    </button>
                </label>
            );
        }


        function vboxElement() {
            return (
                <div class='vbox-vbox'
                    onMouseDown={() => setReclaiming(false)}
                    onClick={e => e.stopPropagation()}>
                    <div class="vbox-hdr">
                        <h3
                            onTouchStart={e => e.target.scrollIntoView(true)}
                            onMouseOver={e => hoverInfo(e, 'vbox')}> VBOX
                        </h3>
                        <div class={`bits ${vbox.bits < 3 ? 'red' : false}`} onMouseOver={e => hoverInfo(e, 'bits')} >{vbox.bits}b</div>
                    </div>
                    <div class="vbox-colours">
                        {range(0, 6).map(i => availableBtn(vbox.free[0][i], 0, i))}
                    </div>
                    <div class="vbox-items">
                        {range(0, 3).map(i => availableBtn(vbox.free[1][i], 1, i))}
                        {range(0, 3).map(i => availableBtn(vbox.free[2][i], 2, i))}
                    </div>
                    <button
                        class='vbox-btn'
                        onMouseOver={e => hoverInfo(e, 'refill')}
                        disabled={tutorial && tutorial < 7 && instance.time_control === 'Practice' && instance.rounds.length === 1}
                        onClick={e => e.stopPropagation()}
                        onMouseDown={() => sendVboxDiscard()}>
                        refill - 2b
                    </button>
                </div>
            );
        }

        //
        //  INVENTORY
        //
        function reclaimClick(e) {
            e.stopPropagation();
            return setReclaiming(!reclaiming);
        }

        const inventoryClass = `vbox-section ${reclaiming ? 'reclaiming' : ''}`;

        function inventoryBtn(v, i) {
            const inventoryHighlight = vboxSelecting || itemUnequip.length;

            if (!v && v !== 0) {
                return <button key={i} disabled={!inventoryHighlight} class={inventoryHighlight ? 'receiving' : 'empty'} >&nbsp;</button>;
            }

            const combinerItems = combiner.map(j => vbox.bound[j]);
            const combinerCount = countBy(combinerItems, co => co);

            const comboItem = itemInfo.combos.find(combo => {
                if (combo.components.includes(v)) {
                    return combinerItems.every(c => {
                        if (!combo.components.includes(c)) return false;
                        const comboCount = countBy(combo.components, co => co);
                        if (combinerCount[c] > comboCount[c]) return false;
                        if (c === v && combinerCount[c] + 1 > comboCount[c]) return false;
                        return true;
                    });
                } return false;
            });
            const comboHighlight = combinerItems.length > 0 && comboItem  ? 'combo-border' : '';

            function onClick(type) {
                if (vboxSelecting) clearVboxSelected();
                if (reclaiming) return sendVboxReclaim(i);

                const combinerContainsIndex = combiner.indexOf(i) > -1;
                // 4 things selected
                if (combiner.length > 2 && !combinerContainsIndex) {
                    setInfo(vbox.bound[i]);
                    return combinerChange([i]);
                }
                // removing
                if (combinerContainsIndex) {
                    if (type === 'click') {
                        return combinerChange(without(combiner, i));
                    }
                    return true;
                }

                if (!comboHighlight && !combinerContainsIndex) {
                    setInfo(vbox.bound[i]);
                    return combinerChange([i]);
                }

                combiner.push(i);
                if (combiner.length === 3) setInfo(comboItem.item);
                return combinerChange(combiner);
            }

            const highlighted = combiner.indexOf(i) > -1;
            const border = buttons[removeTier(v)] ? buttons[removeTier(v)]() : '';
            const classes = `${highlighted ? 'highlight' : border} ${comboHighlight}`;

            const invObject = shapes[v] ? shapes[v]() : v;

            return (
                <label
                    key={i}
                    draggable='true'
                    onDragStart={ev => {
                        onClick('drag');
                        ev.dataTransfer.setData('text', '');
                    }}>
                    <button
                        class={classes}
                        onMouseOver={e => vboxHover(e, v)}
                        onClick={e => e.stopPropagation()}
                        onMouseDown={() => onClick('click')}>
                        {invObject}
                    </button>
                </label>
            );
        }

        function combinerBtn() {
            let text = '';
            let comboItem = '';
            if (combiner.length < 3) {
                for (let i = 0; i < 3; i++) {
                    if (combiner.length > i) {
                        text += '■ ';
                    } else {
                        text += '▫ ';
                    }
                }
            } else {
                // Since theres 3 items in combiner and you can't have invalid combos we can preview it
                const combinerItems = combiner.map(j => vbox.bound[j]);
                const combinerCount = countBy(combinerItems, co => co);
                const comboItemObj = itemInfo.combos.find(combo => combinerItems.every(c => {
                    if (!combo.components.includes(c)) return false;
                    const comboCount = countBy(combo.components, co => co);
                    if (combinerCount[c] > comboCount[c]) return false;
                    return true;
                }));
                comboItem = comboItemObj ? comboItemObj.item : 'refine';
                comboItem = comboItem.replace('Plus', '+');
                text = `Combine - ${comboItem}`;
            }

            return (
                <button
                    class='vbox-btn'
                    disabled={combiner.length !== 3}
                    onMouseOver={e => hoverInfo(e, comboItem)}
                    onClick={e => e.stopPropagation()}
                    onMouseDown={() => sendVboxCombine()}>
                    {text}
                </button>
            );
        }

        function inventoryElement() {
            function inventoryClick(e) {
                e.stopPropagation();
                setReclaiming(false);
                if (vboxSelecting) return vboxBuySelected();
                if (itemUnequip.length) return sendItemUnequip(itemUnequip);
                return true;
            }

            return (
                <div class={inventoryClass}
                    onMouseDown={inventoryClick}
                    onClick={e => e.stopPropagation()}
                    style={vboxSelecting || (itemUnequip.length) ? { cursor: 'pointer' } : null}
                    onDragOver={ev => ev.preventDefault()}
                    onDrop={inventoryClick}
                >
                    <div class="vbox-hdr">
                        <h3
                            onTouchStart={e => e.target.scrollIntoView(true)}
                            onMouseOver={e => hoverInfo(e, 'inventory')}> INVENTORY
                        </h3>
                        <button
                            disabled={tutorial && tutorial < 8 && instance.time_control === 'Practice' && instance.rounds.length === 1}
                            class='vbox-btn reclaim'
                            onMouseOver={e => hoverInfo(e, 'reclaim')}
                            onClick={e => e.stopPropagation()}
                            onMouseDown={reclaimClick}>
                            reclaim
                        </button>
                    </div>
                    <div class='vbox-items'>
                        {range(0, 9).map(i => inventoryBtn(vbox.bound[i], i))}
                    </div>
                    {combinerBtn()}
                </div>
            );
        }

        //
        // EVERYTHING
        //
        function hoverInfo(e, newInfo) {
            e.stopPropagation();
            return setInfo(newInfo);
        }

        const classes = `vbox`;
        return (
            <div class={classes}>
                {vboxElement()}
                <div class="vbox-arrow">⮞</div>
                {inventoryElement()}
            </div>
        );
    }
}

module.exports = addState(Vbox);
