import * as bootstrap from 'bootstrap';
import $ from 'jquery';

interface DownloadButton extends HTMLElement {
    dataset: DOMStringMap & { id?: string };
}

$(function () {
    // Функция для определения языка из URL
    function getLang(): string {
        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 'en'; // По умолчанию английский
    }

    // Переводы
    const translations = {
        en: {
            downloadIdNotFound: 'Download ID not found',
            downloadUrlNotFound: 'Download URL not found',
            largeFilesDetected: '⚠️ Large files detected ({size}). For faster downloads, consider downloading files individually instead of creating an archive.',
            confirmLargeDownload: '⚠️ Total file size is {size}!\n\nDownloading very large archives may take a long time.\n\nFor faster and more reliable downloads, consider downloading files individually (direct download).\n\nContinue with archive download?',
            confirmMediumDownload: '⚠️ Total file size is {size}.\n\nThis may take some time to download.\n\nFor faster downloads, consider downloading files individually.\n\nContinue?',
            startingDownload: 'Starting download...',
            downloadStarted: 'Download started! Check your downloads.',
            totalFileSize: 'Total file size: {size}. Archive creation may take some time.',
            browserWarning: 'Your browser may have limitations with large downloads. For best experience use Chrome, Firefox, Safari or Edge.',
            largeArchiveTooltip: 'Large archive - may take significant time to download',
            largeFileLabel: 'Large',
            // Flash заголовки
            wellDone: 'Well done!',
            ohSnap: 'Oh snap!',
            warning: 'Warning!',
            hiThere: 'Hi there!',
            notice: 'Notice'
        },
        de: {
            downloadIdNotFound: 'Download-ID nicht gefunden',
            downloadUrlNotFound: 'Download-URL nicht gefunden',
            largeFilesDetected: '⚠️ Große Dateien erkannt ({size}). Für schnellere Downloads sollten Sie die Dateien einzeln herunterladen, anstatt ein Archiv zu erstellen.',
            confirmLargeDownload: '⚠️ Gesamtdateigröße beträgt {size}!\n\nDas Herunterladen sehr großer Archive kann lange dauern.\n\nFür schnellere und zuverlässigere Downloads laden Sie die Dateien einzeln herunter (Direktdownload).\n\nMit dem Archiv-Download fortfahren?',
            confirmMediumDownload: '⚠️ Gesamtdateigröße beträgt {size}.\n\nDer Download kann einige Zeit dauern.\n\nFür schnellere Downloads laden Sie die Dateien einzeln herunter.\n\nFortfahren?',
            startingDownload: 'Download wird gestartet...',
            downloadStarted: 'Download gestartet! Überprüfen Sie Ihre Downloads.',
            totalFileSize: 'Gesamtdateigröße: {size}. Die Archivierung kann einige Zeit dauern.',
            browserWarning: 'Ihr Browser hat möglicherweise Einschränkungen bei großen Downloads. Verwenden Sie für beste Ergebnisse Chrome, Firefox, Safari oder Edge.',
            largeArchiveTooltip: 'Großes Archiv - Download kann längere Zeit dauern',
            largeFileLabel: 'Groß',
            // Flash заголовки
            wellDone: 'Gut gemacht!',
            ohSnap: 'Oh nein!',
            warning: 'Warnung!',
            hiThere: 'Hallo!',
            notice: 'Hinweis'
        }
    };

    // Функция для получения перевода
    function t(key: string, params?: { [key: string]: string }): string {
        const lang = getLang();
        const langTranslations = translations[lang as keyof typeof translations] || translations.en;
        let text = langTranslations[key as keyof typeof langTranslations] || translations.en[key as keyof typeof translations.en] || key;

        if (params) {
            Object.keys(params).forEach(param => {
                text = text.replace(`{${param}}`, params[param]);
            });
        }

        return text;
    }

    const tooltipElements = document.querySelectorAll<HTMLElement>("[data-bs-toggle='tooltip']");
    tooltipElements.forEach((el) => {
        new bootstrap.Tooltip(el);
    });

    const noFile = document.getElementById('no_files');
    if (noFile) {
        const downloadAll = document.getElementById('downloadAll');
        downloadAll?.classList.add('d-none');
    }

    // Проверяем общий размер файлов при загрузке страницы
    checkAndShowFileSizeWarning();

    const downloadAllButton = document.getElementById('downloadAllButton') as DownloadButton | null;

    if (downloadAllButton) {
        downloadAllButton.addEventListener('click', function (event) {
            event.preventDefault();

            const id = downloadAllButton.dataset.id;
            if (!id) {
                showFlash('error', t('downloadIdNotFound'));
                return;
            }

            const downloadUrl = (document.getElementById('app_download_all') as HTMLInputElement | null)?.value;
            if (!downloadUrl) {
                showFlash('error', t('downloadUrlNotFound'));
                return;
            }

            // Проверяем размер файлов и показываем предупреждение если нужно
            const totalSizeElement = document.querySelector<HTMLElement>('.col-md-6:first-child');
            if (totalSizeElement) {
                const sizeText = totalSizeElement.textContent || '';
                const sizeMatch = sizeText.match(/(\d+(?:,\d+)?)\s*(GB|MB|TB)/i);

                if (sizeMatch) {
                    const size = parseFloat(sizeMatch[1].replace(',', '.'));
                    const unit = sizeMatch[2].toUpperCase();

                    // Конвертируем в GB для сравнения
                    let sizeInGB = size;
                    if (unit === 'TB') {
                        sizeInGB = size * 1024;
                    } else if (unit === 'MB') {
                        sizeInGB = size / 1024;
                    }

                    // Если больше 2GB, показываем предупреждение с подтверждением
                    if (sizeInGB > 2) {
                        const confirmMessage = sizeInGB > 10
                            ? `⚠️ Total file size is ${sizeMatch[0]}!\n\nDownloading very large archives may take a long time.\n\nFor faster downloads, consider downloading files individually.\n\nContinue with archive download?`
                            : `⚠️ Total file size is ${sizeMatch[0]}.\n\nThis may take some time to download.\n\nContinue?`;

                        if (!confirm(confirmMessage)) {
                            return; // Отменяем скачивание
                        }
                    }
                }
            }

            // Показываем индикатор загрузки
            const originalContent = downloadAllButton.innerHTML;
            downloadAllButton.innerHTML = t('startingDownload') + ' <div class="spinner-border spinner-border-sm" role="status"></div>';
            downloadAllButton.style.pointerEvents = 'none';

            // Для потокового скачивания просто создаем ссылку и кликаем
            // Браузер сам обработает скачивание
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = ''; // Пустое значение позволит использовать имя файла из заголовков ответа
            link.style.display = 'none';

            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            // Быстро восстанавливаем кнопку
            setTimeout(() => {
                downloadAllButton.innerHTML = originalContent;
                downloadAllButton.style.pointerEvents = 'auto';
                showFlash('success', t('downloadStarted'));
            }, 1500);

            // Альтернативный метод через window.location для больших файлов
            // Это заставит браузер начать скачивание немедленно
            // setTimeout(() => {
            //     window.location.href = downloadUrl;
            // }, 100);
        });
    }

    function showFlash(label: string, message: string) {
        const flashContainer = document.getElementById('flash-messages');
        if (!flashContainer) {
            console.error('Can\'t find flash');
            return;
        }

        const headlines = {
            success: t('wellDone'),
            error: t('ohSnap'),
            warning: t('warning'),
            info: t('hiThere'),
            default: t('notice')
        };

        const flashElement = document.createElement('div');
        flashElement.className = `flash-message flash-message--${label}`;
        flashElement.innerHTML = `
                <svg class="svg-${label}" width="84" height="75" viewBox="0 0 84 75" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="20.6075" cy="9.29547" r="9.29547" fill="#004E32"/>
                    <circle cx="80.0986" cy="47.7167" r="3.71819" fill="#004E32"/>
                    <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"/>
                </svg>

                <div class="flash-message__icon">
                    ${label === 'success' ? '✓' : label === 'error' ? '×' : label === 'warning' ? '!' : label === 'info' ? '?' : 'i'}
                </div>
                <div class="flash-message__text">
                    <div class="headline">
                        ${headlines[label as keyof typeof headlines] || headlines.default}
                    </div>
                    <div class="subtext">${message}</div>
                </div>
                <button class="flash-message__close" aria-label="Close">&times;</button>
            `;

        flashContainer.appendChild(flashElement);

        const closeButton = flashElement.querySelector('.flash-message__close');

        if (closeButton) {
            closeButton.addEventListener('click', function () {
                flashElement.remove();
            });
        }

        // Автоматическое скрытие через 5 секунд (10 для warning)
        setTimeout(() => {
            if (flashElement.parentNode) {
                flashElement.remove();
            }
        }, label === 'warning' ? 10000 : 5000);
    }

    // Проверяем размер файлов и показываем предупреждение при загрузке страницы
    function checkAndShowFileSizeWarning() {
        const totalSizeElement = document.querySelector<HTMLElement>('.col-md-6:first-child');
        if (totalSizeElement) {
            const sizeText = totalSizeElement.textContent || '';
            const sizeMatch = sizeText.match(/(\d+(?:,\d+)?)\s*(GB|MB|TB)/i);

            if (sizeMatch) {
                const size = parseFloat(sizeMatch[1].replace(',', '.'));
                const unit = sizeMatch[2].toUpperCase();

                // Конвертируем в GB для сравнения
                let sizeInGB = size;
                if (unit === 'TB') {
                    sizeInGB = size * 1024;
                } else if (unit === 'MB') {
                    sizeInGB = size / 1024;
                }

                // Показываем информационное сообщение для больших файлов
                if (sizeInGB > 10) {
                    showFlash(
                        'warning',
                        `⚠️ Large files detected (${sizeMatch[0]}). For faster downloads, consider downloading files individually instead of creating an archive.`
                    );

                    // Добавляем подсказку к кнопке
                    const downloadAllButton = document.getElementById('downloadAllButton');
                    if (downloadAllButton) {
                        downloadAllButton.setAttribute('title', 'Large archive - may take significant time to download');
                        downloadAllButton.style.position = 'relative';

                        // Добавляем визуальный индикатор
                        const indicator = document.createElement('span');
                        indicator.innerHTML = '⚠️';
                        indicator.style.cssText = 'position: absolute; top: -5px; right: -5px; font-size: 12px;';
                        downloadAllButton.appendChild(indicator);
                    }

                    console.log("size: " + sizeInGB)
                } else if (sizeInGB > 2) {
                    showFlash(
                        'info',
                        `Total file size: ${sizeMatch[0]}. Archive creation may take some time.`
                    );
                }
            }
        }
    }

    // Проверка поддержки браузером больших скачиваний
    function checkBrowserSupport() {
        const isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
        const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
        const isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
        const isEdge = /Edg/.test(navigator.userAgent);

        if (!isChrome && !isFirefox && !isSafari && !isEdge) {
            showFlash('warning', t('browserWarning'));
        }
    }

    // Альтернативный метод скачивания для старых браузеров
    function fallbackDownload(url: string) {
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        iframe.src = url;
        document.body.appendChild(iframe);

        setTimeout(() => {
            document.body.removeChild(iframe);
        }, 5000);
    }

    // Добавляем подсказки для отдельных файлов если они большие
    function addFileSizeHints() {
        const fileButtons = document.querySelectorAll('.button-download-wrapper');
        fileButtons.forEach((button) => {
            const tooltip = button.getAttribute('data-bs-title');
            if (tooltip && /\d+\s*(GB|TB)/i.test(tooltip)) {
                const link = button as HTMLElement;
                link.style.position = 'relative';

                // Можно добавить визуальные индикаторы для больших файлов
                const sizeMatch = tooltip.match(/(\d+(?:\.\d+)?)\s*(GB|TB)/i);
                if (sizeMatch) {
                    const size = parseFloat(sizeMatch[1]);
                    const unit = sizeMatch[2].toUpperCase();

                    if ((unit === 'GB' && size > 1) || unit === 'TB') {
                        const badge = document.createElement('span');
                        badge.className = 'badge bg-warning text-dark';
                        badge.style.cssText = 'position: absolute; top: 5px; right: 5px; font-size: 10px;';
                        badge.textContent = t('largeFileLabel');
                        link.appendChild(badge);
                    }
                }
            }
        });
    }

    checkBrowserSupport();
    addFileSizeHints();
});