import { Modal } from 'bootstrap';
import $ from 'jquery';
import 'datatables.net-bs5';

$(function () {
    const confirmModalElement = document.getElementById('deleteConfirmModal');
    if (confirmModalElement && confirmModalElement.parentElement !== document.body) {
        document.body.appendChild(confirmModalElement);
    }

    function getLang() {
        if (window.location.href.indexOf('/de/') > -1) {
            return 'de';
        }

        if (window.location.href.indexOf('/en/') > -1) {
            return 'en';
        }

        if (window.location.href.indexOf('/es/') > -1) {
            return 'es';
        }
        if (window.location.href.indexOf('/ru/') > -1) {
            return 'ru';
        }
        return 'de';
    }

    const languageOptions = {
        'de': {
            searchPlaceholder: 'Suchen',
            lengthMenu: 'Einträge anzeigen _MENU_'
        },
        'en': {
            searchPlaceholder: 'Search',
            lengthMenu: 'Show _MENU_ entries'
        },
        'es': {
            searchPlaceholder: 'Buscar',
            lengthMenu: 'Mostrar _MENU_ entradas'
        },
        'ru': {
            searchPlaceholder: 'Поиск',
            lengthMenu: 'Показать _MENU_ записей'
        }
    };

    const lang = getLang();
    const langOptions = languageOptions[lang] || languageOptions['en'];

    const table = $('.table-responsive');

    table.on('show.bs.dropdown', function () {
        $('#contactTable').css('overflow', 'inherit');
    });

    table.on('hide.bs.dropdown', function () {
        $('#contactTable').css('overflow', 'auto');
    });

    $('#contactTable').DataTable({
        initComplete: function () {
            $('input[type="search"]').first().focus();
        },

        stateSave: true,
        autoWidth: true,
        paging: true,
        pagingType: 'simple_numbers',
        ordering: true,
        order: [[0, 'desc']],
        columnDefs: [
            {targets: 5, orderable: false},
            {targets: 6, orderable: false}
        ],
        language: {
            search: '',
            searchPlaceholder: langOptions.searchPlaceholder,
            lengthMenu: langOptions.lengthMenu,
            paginate: {
                previous: '<',
                next: '>'
            }
        },
        lengthChange: false,
        lengthMenu: [],
        pageLength: 5,
        dom: 'lfrtp'
    });

    let deleteLink: string | null = null;

    $(document).on('click', '.button-delete-ts', function (event) {
        event.preventDefault();
        deleteLink = $(this).data('delete-link') ?? null;

        const modalElement = document.getElementById('deleteConfirmModal');
        if (modalElement && modalElement.parentElement !== document.body) {
            document.body.appendChild(modalElement);
        }
    });

    $(document).on('show.bs.modal', '#deleteConfirmModal', function () {
        const modal = this as HTMLElement;
        if (modal.parentElement !== document.body) {
            document.body.appendChild(modal);
        }
    });

    $(document).on('click', '#confirmDeleteBtn', function (event) {
        event.preventDefault();
        event.stopPropagation();
        if (deleteLink) {
            window.location.href = deleteLink;
        } else {
            const modalElement = document.getElementById('deleteConfirmModal');
            if (modalElement) {
                Modal.getInstance(modalElement)?.hide();
            }
        }
    });

    const openModalBtn = document.getElementById('open-contact-modal-btn');
    const contactModalEl = document.getElementById('contact-modal');

    if (contactModalEl) {
        if (contactModalEl.parentElement !== document.body) {
            document.body.appendChild(contactModalEl);
        }

        const contactModal = Modal.getOrCreateInstance(contactModalEl, {
            backdrop: 'static',
            keyboard: false,
        });

        const form = document.getElementById('create-contact-form') as HTMLFormElement | null;
        const titleEl = document.getElementById('contact-modal-title');
        const submitEl = document.getElementById('contact-modal-submit');
        const tokenEl = document.getElementById('contact-form-token') as HTMLInputElement | null;
        const firstNameEl = document.getElementById('create_firstName') as HTMLInputElement | null;
        const lastNameEl = document.getElementById('create_lastName') as HTMLInputElement | null;
        const emailEl = document.getElementById('create_email') as HTMLInputElement | null;
        const companyEl = document.getElementById('create_company') as HTMLInputElement | null;
        const cellphoneEl = document.getElementById('create_cellphone') as HTMLInputElement | null;

        const createUrl = contactModalEl.dataset.createUrl || '';
        const createToken = contactModalEl.dataset.createToken || '';
        const updateToken = contactModalEl.dataset.updateToken || '';
        const titleCreate = contactModalEl.dataset.titleCreate || '';
        const titleEdit = contactModalEl.dataset.titleEdit || '';
        const submitCreate = contactModalEl.dataset.submitCreate || '';
        const submitEdit = contactModalEl.dataset.submitEdit || '';

        const setField = (el: HTMLInputElement | null, value: string) => {
            if (el) {
                el.value = value;
            }
        };

        const resetCreateMode = () => {
            contactModalEl.dataset.mode = 'create';
            if (form) {
                form.action = createUrl;
            }
            if (tokenEl) {
                tokenEl.value = createToken;
            }
            if (titleEl) {
                titleEl.textContent = titleCreate;
            }
            if (submitEl) {
                submitEl.textContent = submitCreate;
            }
            setField(firstNameEl, '');
            setField(lastNameEl, '');
            setField(emailEl, '');
            setField(companyEl, '');
            setField(cellphoneEl, '');
        };

        const openCreateModal = () => {
            resetCreateMode();
            contactModal.show();
        };

        const openEditModal = (btn: HTMLElement) => {
            contactModalEl.dataset.mode = 'edit';
            if (form) {
                form.action = btn.dataset.updateUrl || '';
            }
            if (tokenEl) {
                tokenEl.value = updateToken;
            }
            if (titleEl) {
                titleEl.textContent = titleEdit;
            }
            if (submitEl) {
                submitEl.textContent = submitEdit;
            }
            setField(firstNameEl, btn.dataset.firstName || '');
            setField(lastNameEl, btn.dataset.lastName || '');
            setField(emailEl, btn.dataset.email || '');
            setField(companyEl, btn.dataset.company || '');
            setField(cellphoneEl, btn.dataset.cellphone || '');
            contactModal.show();
        };

        if (openModalBtn) {
            openModalBtn.addEventListener('click', openCreateModal);
        }

        $(document).on('click', '.open-contact-edit-btn', function (event) {
            event.preventDefault();
            openEditModal(this as HTMLElement);
        });

        contactModalEl.addEventListener('hidden.bs.modal', () => {
            resetCreateMode();
        });

        contactModalEl.addEventListener('shown.bs.modal', () => {
            firstNameEl?.focus();
        });
    }
});
