/**
 * Multi Select Boxes
 */
import IGDATAPOOLFE from '@dp/ig_datapool_fe.js';

const selectBoxPlugin = {
    initFields(form) {
        this.init(form);
    },

    init(form) {
        const formEl = form instanceof HTMLElement ? form : document.querySelector(form);
        this.form = formEl;

        formEl.querySelectorAll('.dp-multiSelectBox').forEach((field) => {
            const leftSelect = field.querySelector('select.left');
            const rightSelect = field.querySelector('select.right');
            const filterInput = field.querySelector('input.filter');
            const nameTemplate = field.dataset.nametemplate;

            if (!leftSelect || !rightSelect) return;

            // --- Activation / Deactivation ---
            const activate = (options) => {
                options.forEach(opt => {
                    leftSelect.appendChild(opt);
                    opt.selected = false;

                    // Add hidden input
                    const hidden = document.createElement('input');
                    hidden.type = 'hidden';
                    hidden.name = nameTemplate;
                    hidden.value = opt.value;
                    field.appendChild(hidden);
                });
            };

            const deactivate = (options) => {
                options.forEach(opt => {
                    rightSelect.appendChild(opt);
                    opt.selected = false;

                    const hidden = field.querySelector(`input[type="hidden"][value="${opt.value}"]`);
                    if (hidden) hidden.remove();
                });
            };

            // --- Filter ---
            let filterTimeout;
            const doFilter = () => {
                if (!filterInput) return;

                const ajaxUrl = filterInput.dataset.ajaxUrl;
                const delay = parseInt(filterInput.dataset.delay || 300, 10);

                if (ajaxUrl) {
                    clearTimeout(filterTimeout);
                    filterTimeout = setTimeout(() => {
                        rightSelect.innerHTML = ''; // clear options
                        fetch(`${ajaxUrl}?term=intern&_type=query&q=${encodeURIComponent(filterInput.value)}`, { cache: 'no-store' })
                            .then(res => res.json())
                            .then(data => {
                                const selectedValues = Array.from(leftSelect.options).map(opt => parseInt(opt.value));
                                if (data.debug === filterInput.value) {
                                    data.results.forEach(item => {
                                        if (!selectedValues.includes(item.id)) {
                                            const opt = new Option(item.text, item.id);
                                            rightSelect.add(opt);
                                        }
                                    });
                                }
                            })
                            .catch(err => {
                                console.error(err);
                            });
                    }, delay);
                } else {
                    const str = filterInput.value.toUpperCase();
                    Array.from(rightSelect.options).forEach(opt => {
                        opt.hidden = str !== '' && !opt.text.toUpperCase().includes(str);
                    });
                }
            };

            // --- Initialize ---
            activate(Array.from(rightSelect.selectedOptions));

            // --- Right select click → move to left ---
            rightSelect.addEventListener('click', () => {
                const selected = Array.from(rightSelect.selectedOptions);
                activate(selected);

                if (leftSelect.selectedOptions.length) {
                    field.querySelectorAll('.dp-sprite').forEach(sprite => sprite.classList.add('dp-sprite-show'));
                }
            });

            // --- Delete selected ---
            field.querySelectorAll('.dp-sprite.dp-delete').forEach(btn => {
                btn.addEventListener('click', () => {
                    const selected = Array.from(leftSelect.selectedOptions);
                    deactivate(selected);
                    doFilter();

                    if (leftSelect.selectedOptions.length === 0) {
                        field.querySelectorAll('.dp-sprite').forEach(sprite => sprite.classList.remove('dp-sprite-show'));
                    }
                });
            });

            // --- Move up ---
            field.querySelectorAll('.dp-sprite.up').forEach(btn => {
                btn.addEventListener('click', () => {
                    const selected = Array.from(leftSelect.selectedOptions);
                    if (!selected.length) return;
                    const first = selected[0];

                    selected.forEach(opt => {
                        const prev = opt.previousElementSibling;
                        if (prev) {
                            leftSelect.insertBefore(opt, prev);

                            const hidden = field.querySelector(`input[type="hidden"][value="${opt.value}"]`);
                            if (hidden && hidden.previousElementSibling) {
                                hidden.parentNode.insertBefore(hidden, hidden.previousElementSibling);
                            }
                        }
                    });
                });
            });

            // --- Move down ---
            field.querySelectorAll('.dp-sprite.down').forEach(btn => {
                btn.addEventListener('click', () => {
                    const selected = Array.from(leftSelect.selectedOptions);
                    if (!selected.length) return;
                    const last = selected[selected.length - 1];

                    selected.forEach(opt => {
                        const next = last.nextElementSibling;
                        if (next) {
                            leftSelect.insertBefore(opt, next.nextSibling);

                            const hidden = field.querySelector(`input[type="hidden"][value="${opt.value}"]`);
                            if (hidden && hidden.nextElementSibling) {
                                hidden.parentNode.insertBefore(hidden, hidden.nextElementSibling.nextSibling);
                            }
                        }
                    });
                });
            });

            // --- Filter input ---
            if (filterInput) {
                filterInput.addEventListener('keyup', doFilter);
            }
        });
    }
};

IGDATAPOOLFE.addPlugin('selectBox', selectBoxPlugin);
export default selectBoxPlugin;