/**
 * Tabs
 */
import IGDATAPOOLFE from '@dp/ig_datapool_fe.js';

const tabPlugin = {
    init(form) {
        this.form = form;

        this.tabPages = form.querySelectorAll('.dp-tabContainer .dp-tabPage');
        this.tabHeaders = form.querySelectorAll('.dp-tabHeader');
        this.tabDrawers = form.querySelectorAll('.dp-tabDrawer');

        if (form.classList.contains('dp-form-stepsform')) {
            const stepField = form.querySelector('input.currentStep');

            this.tabHeaders.forEach(header => {
                header.addEventListener('click', () => {
                    stepField.value = header.dataset.rel;
                    form.querySelector('form')?.submit();
                });
            });

            this.tabDrawers.forEach(drawer => {
                drawer.addEventListener('click', () => {
                    stepField.value = drawer.dataset.rel;
                    form.submit();
                });
            });

            return;
        }

        this.tabHeaders.forEach(header => {
            header.addEventListener('click', (e) => {
                e.preventDefault();
                this.activateTab(header);
            });
        });

        this.tabDrawers.forEach(drawer => {
            drawer.addEventListener('click', (e) => {
                e.preventDefault();
                this.activateTab(drawer);
            });
        });

        // activate first tab with error or first tab
        let tabToActivate = form.querySelector('.dp-tabHeader.dp-tabHeader-error');
        if (!tabToActivate) {
            tabToActivate = this.tabHeaders[0];
        }

        if (tabToActivate) {
            this.activateTab(tabToActivate);
        }
    },

    activateTab(tabHeader) {
        const tabNumber = tabHeader.dataset.rel;

        // remove active classes
        this.tabHeaders.forEach(el => el.classList.remove('dp-tabHeader-active'));
        this.tabDrawers.forEach(el => el.classList.remove('dp-tabDrawer-active'));

        // activate current
        this.tabHeaders.forEach(el => {
            if (el.classList.contains(`dp-tabHeader-${tabNumber}`)) {
                el.classList.add('dp-tabHeader-active');
            }
        });

        this.tabDrawers.forEach(el => {
            if (el.classList.contains(`dp-tabDrawer-${tabNumber}`)) {
                el.classList.add('dp-tabDrawer-active');
            }
        });

        // content
        this.tabPages.forEach(page => page.style.display = 'none');

        const link = tabHeader.querySelector('a');
        if (link) {
            const target = this.form.querySelector(link.getAttribute('href'));
            if (target) target.style.display = '';
        }

        this.form.dispatchEvent(new Event('tab_changed'));
    },

    /**
     * File Upload Language Pulldown
     */
    initLanguageFileUpload() {
        const selects = this.form.querySelectorAll('.dp-file-upload-lang-select');

        selects.forEach(select => {
            select.addEventListener('change', () => {
                const value = select.value;
                const upload = select.nextElementSibling;

                if (upload && upload.classList.contains('dp-file-upload-lang-upload')) {
                    upload.style.display = value === '' ? '' : 'none';
                }

                const selectedOption = select.options[select.selectedIndex];
                const parent = select.closest('.dp-generalinline-innerrow');
                const textareas = parent ? parent.querySelectorAll('textarea') : [];

                if (selectedOption?.classList.contains('dp-no')) {
                    textareas.forEach(t => t.disabled = true);
                } else {
                    textareas.forEach(t => t.disabled = false);
                }
            });

            const selectedOption = select.options[select.selectedIndex];
            if (
                selectedOption?.classList.contains('dp-no') &&
                selectedOption.offsetParent !== null
            ) {
                const parent = select.closest('.dp-generalinline-innerrow');
                const textareas = parent ? parent.querySelectorAll('textarea') : [];
                textareas.forEach(t => t.disabled = true);
            }
        });

        // sorting up
        this.form.querySelectorAll('.dp-sorting-up').forEach(btn => {
            btn.addEventListener('click', () => {
                const el = btn.closest('.dp-generalinline-record');
                if (!el || !el.previousElementSibling) return;

                const prev = el.previousElementSibling;

                const curInput = el.querySelector('input.dp-file-upload-sort');
                const prevInput = prev.querySelector('input.dp-file-upload-sort');

                const curVal = curInput.value;
                curInput.value = prevInput.value;
                prevInput.value = curVal;

                prev.parentNode.insertBefore(el, prev);

                this.form.initFields?.([el]);
            });
        });

        // sorting down
        this.form.querySelectorAll('.dp-sorting-down').forEach(btn => {
            btn.addEventListener('click', () => {
                const el = btn.closest('.dp-generalinline-record');
                if (!el || !el.nextElementSibling) return;

                const next = el.nextElementSibling;

                const curInput = el.querySelector('input.dp-file-upload-sort');
                const nextInput = next.querySelector('input.dp-file-upload-sort');

                const curVal = curInput.value;
                curInput.value = nextInput.value;
                nextInput.value = curVal;

                next.parentNode.insertBefore(next, el);

                this.form.initFields?.([el]);
            });
        });
    }
};

IGDATAPOOLFE.addPlugin('tab', tabPlugin);

export default tabPlugin;