import('bootstrap');
import $ from 'jquery';

$(function () {
    const element = $('#user_settings_myLink')
    const id = $('#id').val() as number;

    function showFlash(label: any, message: any) {
        var flashContainer = document.getElementById('flash-messages');
        if (!flashContainer) {
            console.error('Can\'t find flash');
            return;
        }
        var flashElement = document.createElement('div');
        flashElement.className = "flash-message flash-message--".concat(label);
        flashElement.innerHTML = "\n                <svg class=\"svg-".concat(label, "\" width=\"84\" height=\"75\" viewBox=\"0 0 84 75\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n                    <circle cx=\"20.6075\" cy=\"9.29547\" r=\"9.29547\" fill=\"#004E32\"/>\n                    <circle cx=\"80.0986\" cy=\"47.7167\" r=\"3.71819\" fill=\"#004E32\"/>\n                    <path d=\"M79.4438 11.0253C82.4971 18.5483 78.8737 27.1221 71.3507 30.1754C70.5208 30.5122 69.6781 30.7678 68.8315 30.9458C64.1204 31.9366 58.8591 33.2841 56.3382 37.3855C53.3951 42.1741 55.0036 48.3927 59.3496 51.9571C68.015 59.0642 75.0268 68.4315 79.3829 79.6187C92.9059 114.348 75.7149 153.464 40.9856 166.987C6.25636 180.51 -32.8599 163.319 -46.3829 128.59C-59.9059 93.8607 -42.7149 54.7445 -7.98562 41.2214C7.18342 35.3148 23.1894 35.2678 37.5341 39.9824C42.7299 41.69 48.6536 40.072 51.5174 35.4125L52.5823 33.68C54.694 30.2441 53.7172 25.8191 52.2006 22.0823C49.1473 14.5592 52.7707 5.98544 60.2937 2.93215C67.8167 -0.121136 76.3906 3.5023 79.4438 11.0253Z\" fill=\"#004E32\"/>\n                </svg>\n\n                <div class=\"flash-message__icon\">\n                    ").concat(label === 'success' ? '✓' : label === 'error' ? '×' : label === 'warning' ? '!' : label === 'info' ? '?' : 'i', "\n                </div>\n                <div class=\"flash-message__text\">\n                    <div class=\"headline\">\n                        ").concat(label === 'success' ? 'Well done!' : label === 'error' ? 'Oh snap!' : label === 'warning' ? 'Warning!' : label === 'info' ? 'Hi there!' : 'Notice', "\n                    </div>\n                    <div class=\"subtext\">").concat(message, "</div>\n                </div>\n                <button class=\"flash-message__close\" aria-label=\"Close\">&times;</button>\n            ");
        flashContainer.appendChild(flashElement);
        var closeButton = flashElement.querySelector('.flash-message__close');
        if (closeButton) {
            closeButton.addEventListener('click', function () {
                flashElement.remove();
            });
        }
        // Автоматическое скрытие через 5 секунд
        setTimeout(function () {
            if (flashElement.parentNode) {
                flashElement.remove();
            }
        }, 5000);
    }


    function previewAvatar(event: Event): void {
        const defaultImage = document.getElementById('default-account-image') as HTMLElement;
        const input = event.target as HTMLInputElement;
        const saveButton = document.getElementById('saveButton') as HTMLButtonElement;

        if (!input || !input.files || input.files.length === 0) {
            return;
        }

        const file = input.files[0];
        const reader = new FileReader();

        reader.onload = (e: ProgressEvent<FileReader>) => {
            const preview = document.getElementById('avatarPreview') as HTMLImageElement;
            if (preview) {
                preview.src = e.target?.result as string;
                preview.style.display = 'block';
            }
            if (defaultImage) {
                defaultImage.style.display = 'none';
            }
            // Show the save button when a file is selected
            if (saveButton) {
                saveButton.style.display = 'inline';
            }
        };

        reader.readAsDataURL(file);
    }

    $(document).ready(() => {
        const avatarInput = document.querySelector('input[type="file"]');
        if (avatarInput) {
            avatarInput.addEventListener('change', previewAvatar);
        }
    });

    $('#del_account_image').on('click', function () {
        const deleteUrl = $('#delete-avatar-url').val() as string;
        if (!deleteUrl) {
            console.error('Delete avatar URL not found');
            return;
        }
        $('#output_del_account_image').load(deleteUrl, function () {
            location.reload();
        });
    });

    // 2FA Toggle functionality
    $('#two-factor-toggle').on('change', function () {
        const isEnabled = $(this).is(':checked');
        const userId = $(this).data('user-id');
        const toggle2faUrl = $('#toggle-2fa-url').val() as string;

        if (!toggle2faUrl) {
            console.error('Toggle 2FA URL not found');
            $('#two-factor-toggle').prop('checked', !isEnabled);
            showNotification('Error: Route configuration missing', 'error');
            return;
        }

        $.ajax({
            url: toggle2faUrl,
            method: 'POST',
            data: {
                enabled: isEnabled,
                userId: userId
            },
            success: function(response) {
                if (response.success) {
                    // Show success message
                    showNotification('2FA ' + (isEnabled ? 'enabled' : 'disabled') + ' successfully', 'success');
                } else {
                    // Revert toggle state on error
                    $('#two-factor-toggle').prop('checked', !isEnabled);
                    showNotification(response.error || 'Failed to update 2FA status', 'error');
                }
            },
            error: function() {
                // Revert toggle state on error
                $('#two-factor-toggle').prop('checked', !isEnabled);
                showNotification('Error updating 2FA status', 'error');
            }
        });
    });

    // Simple notification function
    function showNotification(message: string, type: any) {
        showFlash(type, message);
    }
});
