import ModalAddLanguage from "../Modals/ModalAddLanguage";
import NumberUtil from "../../Utils/NumberUtil";
import Toastr from "../../Utils/Toastr";

class Languages {
    _addLangModal;

    init() {
        if (!jQuery('#languages-pane')[0]) {
            return;
        }
        const _this = this;
        this._addLangModal = new ModalAddLanguage('modal-new-lang', {
            saveCallback: data => {
                _this._handleSaveCallback(data);
            }
        });
        this._handleEvents();
    }

    _handleSaveCallback(data) {
        const { type, code, countryCode } = data;
        switch (type) {
            case 'edit':
                if (code !== countryCode) {
                    this._changeLanguage(data);
                } else {
                    alert(`${window?.OXYLEAF_ADMIN_SETTINGS?.labels?.existing_lang_msg}`);
                }
                break;
            case 'new':
                this._addLanguage(data);
                break;
        }
    }

    _changeLanguage(data) {
        const { code, itemUI, image } = data;
        itemUI.attr('data-lang', code);
        itemUI.find('.skl-flag img').attr('src', image);
        itemUI.find('.skl-code-upper').html(code.toUpperCase());
        itemUI.find('.skp-lang-input').each(function(index) {
            const name = jQuery(this).attr('name');
            const updatedName = name.replace(/(\[.*?\])\[(.*?)\]/, `$1[${code}]`);
            jQuery(this).attr('name', updatedName);
        })
    }

    _addLanguage(data) {
        if (!jQuery('.main-lang')[0]) {
            return;
        }
        const { code, itemUI, image } = data;
        if (jQuery(`[data-lang="${code}"]`)[0]) {
            alert(`${window?.OXYLEAF_ADMIN_SETTINGS?.labels?.existing_lang_msg}`);
            return;
        }

        const tempUI = jQuery('.main-lang').clone();
        tempUI.attr('data-lang', code);
        tempUI.find('.skl-flag img').attr('src', image);
        tempUI.find('.skl-code-upper').html(code.toUpperCase());
        tempUI.find('.skp-lang-input').each(function(index) {
            const name = jQuery(this).attr('name');
            const updatedName = name.replace(/(\[.*?\])\[(.*?)\]/, `$1[${code}]`);
            jQuery(this).attr('name', updatedName);
            const newId = `ids_${NumberUtil.getRandomInt(0, 100000000)}`;
            jQuery(this).attr('id', newId);
            jQuery(this).parent().find('.skp-lang-input-label').attr('for', newId);
        })
        const random = `collapse${NumberUtil.getRandomInt(0, 100000000)}`;
        tempUI.find('.accordion-button').attr('data-bs-target', `#${random}`);
        tempUI.find('.accordion-button').attr('aria-controls', random);
        tempUI.find('.accordion-collapse').attr('id', random);
        tempUI.removeClass('main-lang')
        tempUI.appendTo('#langs-accordion');
        jQuery('.accordion-item .accordion-collapse').removeClass('show');
        jQuery(`<button type="button" class="btn btn-outline-danger btn-sm skl-delete-lang">${window?.OXYLEAF_ADMIN_SETTINGS?.labels?.delete_lang_btn_label}</button>`).appendTo(tempUI.find('.lang-navs'));
        this._accordionItemEvents(tempUI);
        const accordionItems = document.querySelectorAll('#langs-accordion .accordion-collapse');
        // Destroy existing instances (if any)
        accordionItems.forEach(item => {
            const instance = bootstrap.Collapse.getInstance(item);
            if (instance) {
                instance.dispose(); // Clean up the instance
            }
        });
      
        // Recreate Bootstrap Collapse instances
        accordionItems.forEach(item => {
            new bootstrap.Collapse(item, {
                toggle: false // Prevent immediate toggling
            });
        });

        Toastr.success(`${code.toUpperCase()} - ${window?.OXYLEAF_ADMIN_SETTINGS?.labels?.success_language_added}`);
    }

    _handleEvents() {
        const _this = this;
        jQuery('#add_new_lang_btn').on('click', function(event) {
            _this._addLangModal.open({
                type: 'new'
            });
        })

        jQuery('.accordion-item').each(function(index) {
            _this._accordionItemEvents(jQuery(this));
        })
    }

    _accordionItemEvents(itemUI) {
        const _this = this;
        itemUI.find('.skl-change-lang').on('click', function(event) {
            event.preventDefault();
            const currentAccItem = jQuery(this).parent().parent().parent();
            const currentLangCode = currentAccItem.data('lang');
            _this._addLangModal.open({
                countryCode: currentLangCode, itemUI, type: 'edit'
            });
        })

        itemUI.find('.skl-delete-lang').on('click', function(event) {
            event.preventDefault();
            if (confirm(`${window?.OXYLEAF_ADMIN_SETTINGS?.labels?.delete_lang_msg}`)) {
                itemUI.remove();
            }
        })
    }
}
export default Languages;