jQuery(function ($) {
    var cfg = window.W5EBulkOrder || {};
    var action = cfg.action || '';
    var warehouses = Array.isArray(cfg.warehouses) ? cfg.warehouses : [];

    if (!action) {
        return;
    }

    function buildSelect(id) {
        var $select = $('<select/>', {
            id: id,
            'class': 'w5e-bulk-warehouse-select'
        });
        var placeholder = (cfg.i18n && cfg.i18n.selectWarehouse) || 'Select warehouse';
        $select.append($('<option/>', { value: '', text: placeholder }));
        warehouses.forEach(function (row) {
            if (!row || !row.value) {
                return;
            }
            $select.append($('<option/>', {
                value: row.value,
                text: row.label || row.value
            }));
        });
        return $select;
    }

    function attach($actionSelect, suffix) {
        var $wrap = $('<span/>', {
            'class': 'w5e-bulk-warehouse-wrap',
            style: 'margin-left:8px;'
        });
        var labelText = (cfg.i18n && cfg.i18n.label) || 'Warehouse';
        var $label = $('<label/>', {
            'for': 'w5e-bulk-warehouse-' + suffix,
            text: labelText + ' '
        });
        var $select = buildSelect('w5e-bulk-warehouse-' + suffix);
        $wrap.append($label).append($select);
        var $container = $actionSelect.closest('.bulkactions');
        if (!$container.length) {
            $container = $actionSelect.parent();
        }
        if (!$container.length) {
            $container = $actionSelect.closest('form');
        }
        $container.append($wrap);
        return $select;
    }

    var $topAction = $('#bulk-action-selector-top');
    var $bottomAction = $('#bulk-action-selector-bottom');
    if (!$topAction.length && !$bottomAction.length) {
        return;
    }

    function ensureHidden($context) {
        var $form = $context.closest('form');
        if (!$form.length) {
            $form = $('#posts-filter');
        }
        if (!$form.length) {
            $form = $('form#order-list');
        }
        if ($form.length && !$form.find('#w5e-bulk-warehouse-id').length) {
            $form.append($('<input/>', {
                type: 'hidden',
                id: 'w5e-bulk-warehouse-id',
                name: 'w5e_bulk_warehouse_id',
                value: ''
            }));
        }
        return $form;
    }

    var $topSelect = $topAction.length ? attach($topAction, 'top') : $();
    var $bottomSelect = $bottomAction.length ? attach($bottomAction, 'bottom') : $();
    if ($topAction.length) {
        ensureHidden($topAction);
    } else if ($bottomAction.length) {
        ensureHidden($bottomAction);
    }

    function setHidden(value, $context) {
        var $form = $context && $context.length ? ensureHidden($context) : null;
        var $hidden = $form && $form.length ? $form.find('#w5e-bulk-warehouse-id') : $('#w5e-bulk-warehouse-id');
        if ($hidden.length) {
            $hidden.val(value || '');
        }
        if ($topSelect.length && $topSelect.val() !== value) {
            $topSelect.val(value);
        }
        if ($bottomSelect.length && $bottomSelect.val() !== value) {
            $bottomSelect.val(value);
        }
    }

    function toggle() {
        var topActive = $topAction.val() === action;
        var bottomActive = $bottomAction.val() === action;

        if ($topSelect.length) {
            $topSelect.closest('.w5e-bulk-warehouse-wrap').toggle(topActive);
            $topSelect.prop('disabled', !topActive);
        }
        if ($bottomSelect.length) {
            $bottomSelect.closest('.w5e-bulk-warehouse-wrap').toggle(bottomActive);
            $bottomSelect.prop('disabled', !bottomActive);
        }

        if (!topActive && !bottomActive) {
            setHidden('');
        }
    }

    $topAction.on('change', toggle);
    $bottomAction.on('change', toggle);
    $topSelect.on('change', function () {
        setHidden($(this).val(), $(this));
    });
    $bottomSelect.on('change', function () {
        setHidden($(this).val(), $(this));
    });

    $('#doaction, #doaction2').on('click', function (e) {
        var actionVal = this.id === 'doaction' ? $topAction.val() : $bottomAction.val();
        if (actionVal !== action) {
            return;
        }
        var $select = this.id === 'doaction' ? $topSelect : $bottomSelect;
        var value = $select.length ? $select.val() : '';
        if (!value) {
            value = $('#w5e-bulk-warehouse-id').val();
        }
        if (value) {
            setHidden(value, $select.length ? $select : $(this));
        }
        if (!value) {
            e.preventDefault();
            alert((cfg.i18n && cfg.i18n.missingWarehouse) || 'Select a warehouse before applying this bulk action.');
        }
    });

    toggle();
});
