import('bootstrap');
import $ from 'jquery';
import 'datatables.net-bs5';
import 'select2';

require('jquery-circle-progress');

$(function () {
    $('#example').DataTable();
});

$(function () {

    // Функция для проверки email
    // Функция для проверки email
// Функция для проверки email
    function validateEmail(email : any) {
        const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
        return emailPattern.test(email);
    }

// Обработчик для select2
    $('.select-contact').each(function () {
        $(this)
            .select2({
                createTag: function (params) {
                    $('#newContactButtonWrap').hide();

                    const emailValid = validateEmail(params.term);

                    // Валидация при вводе вручную
                    if (params.term && !emailValid) {
                        $('#emailErrorMessage').text(getErrorMessage(getLang())).show();
                    } else {
                        $('#emailErrorMessage').hide();
                    }

                    return {
                        id: params.term,
                        text: 'Email: ' + params.term,
                    };
                },
                tags: true,
                language: getLang(),
                placeholder: $(this).data('placeholder'),
                allowClear: Boolean($(this).data('allow-clear')),
                minimumInputLength: 2,
                theme: 'bootstrap-5',
                ajax: {
                    delay: 300,
                    url: '/app/de/hochladen/find-contacts',
                    data: function (params) {
                        return {
                            query: params.term,
                            action: 'getContactsByQuery',
                        };
                    },
                },
            })
            .on('select2:open', function () {
                setTimeout(function () {
                    $('.select2-container--open .select2-search__field')[0].focus();
                }, 100);
            });
    });

// Обработчик для выбора контакта
    $('.select-contact').on('select2:select', function (e) {
        const selectedData = e.params.data;

        if (selectedData && selectedData.text) {
            const selectedText = selectedData.text;

            // Используем регулярное выражение для поиска email
            const emailMatch = selectedText.match(/[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/);

            if (emailMatch) {
                const selectedEmail = emailMatch[0];  // Извлекаем email
                console.log('SE = ' + selectedEmail);

                // Проверяем валидность email
                if (validateEmail(selectedEmail)) {
                    $('#emailErrorMessage').hide();  // Если email валиден, скрываем ошибку
                } else {
                    $('#emailErrorMessage').text(getErrorMessage(getLang())).show();  // Если невалиден, показываем ошибку
                }
            } else {
                $('#emailErrorMessage').text(getErrorMessage(getLang())).show();  // Если не найден email
            }
        }
    });

// Обработчик закрытия select2, чтобы скрыть ошибку
    $('.select-contact').on('select2:close', function () {
        const currentValue = $(this).val();
        const selectedData = $(this).select2('data');  // Получаем данные выбранного элемента

        if (!currentValue || validateEmail(currentValue)) {
            $('#emailErrorMessage').hide();
        } else if (selectedData && selectedData.length > 0) {
            const selectedText = selectedData[0].text;
            const emailMatch = selectedText.match(/[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/);

            if (emailMatch && validateEmail(emailMatch[0])) {
                $('#emailErrorMessage').hide();
            } else {
                $('#emailErrorMessage').text(getErrorMessage(getLang())).show();
            }
        }
    });

// Очистка ошибки при сбросе значения
    $('.select-contact').on('select2:clear', function () {
        $('#emailErrorMessage').hide();
    });

// Валидация при удалении выбора
    $('.select-contact').on('select2:unselect', function () {
        const currentValue = $(this).val();
        if (!currentValue || validateEmail(currentValue)) {
            $('#emailErrorMessage').hide();
        }
    });



    if ($('#circle').length) {
        // @ts-ignore
        var c4 = $('#circle').circleProgress({
            value: 0,
            size: 100,
            animation: false,
            fill: {
                gradient: ['blue', 'cyan'],
            },
        });

        $('#fileUpload').on('change', function () {
            // @ts-ignore
            var file = (this as HTMLInputElement).files[0];
            var formData = new FormData();
            formData.append('file', file);

            $.ajax({
                url: 'YOUR_UPLOAD_ENDPOINT',
                type: 'POST',
                data: formData,
                processData: false, // tell jQuery not to process the data
                contentType: false, // tell jQuery not to set contentType
                xhr: function () {
                    var xhr = new window.XMLHttpRequest();

                    // Upload progress
                    xhr.upload.addEventListener(
                        'progress',
                        function (evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                // Update the circle progress
                                console.log(percentComplete.toFixed(2));

                                let x = setTimeout(function () {
                                    c4.circleProgress('value', percentComplete);
                                }, 1000);

                                $(c4)
                                    .find('strong')
                                    .html(
                                        Math.round(percentComplete * 100) +
                                        '<i>%</i>'
                                    );
                            }
                        },
                        false
                    );

                    return xhr;
                },
                success: function (data) {
                    console.log('File has been uploaded successfully');
                },
                error: function (err) {
                    console.error('Error during the file upload:', err);
                },
            });
        });
    }

    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';
    }

    function getErrorMessage(lang: any) {
        const errorMessages = {
            de: 'Ungültige E-Mail-Adresse',  // Немецкий
            en: 'Invalid email address',     // Английский
            es: 'Dirección de correo no válida',  // Испанский
            ru: 'Некорректный email'          // Русский
        };

        return errorMessages[lang] || errorMessages['de']; // По умолчанию немецкий
    }

});


