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

$(function () {
    const id: number = $('#id').val() as number

    const fullLinkElement = $('#fullLink') as JQuery<HTMLInputElement>;
    const copyButton = $('#copyMyLink') as JQuery<HTMLButtonElement>;
    const newLinkElement = $('#newLink') as JQuery<HTMLInputElement>;
    const user_settings_myLink = $('#user_settings_myLink');
    const outputLink = $('#output_myLink') as JQuery<HTMLElement>;

    let previousLinkValue = user_settings_myLink.val() as string;


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

    // Функция для копирования ссылки в буфер обмена
    copyButton.on('click', function () {
        fullLinkElement.select();
        document.execCommand("copy");
    });

    newLinkElement.on('input', function () {
        const newLink = (newLinkElement.val() as string).trim();

        if (newLink.length >= 2) {
            user_settings_myLink.val(newLink);
            const lang = getLang();
            outputLink.load(`/app/${lang}/settings/check-company-link?data=${newLink}`);
        } else if (newLink.length === 0) {
            user_settings_myLink.val(previousLinkValue);
            outputLink.empty();
        }
    });


    const signature = document.getElementById('user_settings_companySignature') as HTMLInputElement;
    const subject = document.getElementById('user_settings_emailSubject') as HTMLInputElement;
    const signaturePreview = document.getElementById('signature-preview');
    const subjectPreview = document.getElementById('subject-preview');

    function updatePreview() {
        if (subject.value && subjectPreview) {
            subjectPreview.textContent = subject.value;
        }
        if (signature.value && signaturePreview) {
            // Замените символы новой строки на <br>
            signaturePreview.innerHTML = signature.value.replace(/\n/g, '<br>');
        }
    }

    if (signature && subject) {
        updatePreview()
        signature.addEventListener('input', updatePreview);
        subject.addEventListener('input', updatePreview);
    }

    function previewBackground(event: Event, previewId: string, previewName: string, errorId: string): void {
        const input = event.target as HTMLInputElement;
        const errorMessageDiv = document.getElementById(errorId);
        if (!input || !input.files || input.files.length === 0) {
            return;
        }

        const file = input.files[0];

        // Проверяем размер файла
        if (file.size > 1 * 1024 * 1024) { // 1 MB
            if (errorMessageDiv) {
                errorMessageDiv.textContent = 'Die Datei ist zu groß. Die maximale Größe beträgt 1 MB.';
            }
            input.value = ''; // Очищаем поле
            return; // Выходим из функции
        } else {
            // Очищаем сообщение об ошибке, если файл в порядке
            if (errorMessageDiv) {
                errorMessageDiv.textContent = '';
            }
        }

        const reader = new FileReader();
        reader.onload = (e: ProgressEvent<FileReader>) => {
            const preview = document.getElementById(previewId) as HTMLImageElement;
            if (preview) {
                preview.src = e.target?.result as string;
                preview.style.display = 'block';
            }
            const previewNameDiv = document.getElementById(previewName);
            if (previewNameDiv) {
                previewNameDiv.textContent = file.name;
            }
        };

        reader.readAsDataURL(file);
    }

    function previewLogo(event: Event, previewId: string): void {
        const input = event.target as HTMLInputElement;
        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(previewId) as HTMLImageElement;
            if (preview) {
                preview.src = e.target?.result as string;
                preview.style.display = 'block';
            }
            const fileNameDiv = document.getElementById('fileName');
            if (fileNameDiv) {
                fileNameDiv.textContent = file.name;
            }
        };

        reader.readAsDataURL(file);
    }

    function setActiveTab(tabId: string) {
        const tabs = ['settings', 'background', 'email-template', 'social-media'];
        tabs.forEach(tab => {
            $(`#link-${tab}`).removeClass('active');
            $(`#${tab}-block`).removeClass('display-block').addClass('display-none');
        });
        $(`#link-${tabId}`).addClass('active');
        $(`#${tabId}-block`).removeClass('display-none').addClass('display-block');
        localStorage.setItem('activeTab', tabId);
    }

    function changeActiveTab(tabId: string) {
        localStorage.setItem('activeTab', tabId);
        window.location.reload()
    }

    const activeTab = localStorage.getItem('activeTab') || 'settings';
    setActiveTab(activeTab);

    $('#link-settings').on('click', function () {
        changeActiveTab('settings');
    });

    $('#link-background').on('click', function () {
        changeActiveTab('background');
    });

    $('#link-email-template').on('click', function () {
        changeActiveTab('email-template');
    });

    $('#link-social-media').on('click', function () {
        changeActiveTab('social-media');
    });


    $('#del_background_login').on('click', function () {
        $('#output_del_background_login').load('/app/' + getLang() + '/settings/' + id + '/delete-image?type=login', function () {
            location.reload()
        })
    })

    $('#del_background_upload').on('click', function () {
        $('#output_del_background_upload').load('/app/' + getLang() + '/settings/' + id + '/delete-image?type=upload', function () {
            location.reload()
        })
    })

    $('#del_background_download').on('click', function () {
        $('#output_del_background_download').load('/app/' + getLang() + '/settings/' + id + '/delete-image?type=download', function () {
            location.reload()
        })
    })
    $('#del_email_logo').on('click', function () {
        $('#output_del_email_logo').load('/app/' + getLang() + '/settings/' + id + '/delete-image?type=logo', function () {
            location.reload()
        })
    })


    $(document).ready(() => {
        const loginInput = document.querySelector('input[id="user_settings_background_login"]');
        if (loginInput) {
            loginInput.addEventListener('change', (event) =>
                previewBackground(event, 'loginBackgroundPreview', 'loginBackgroundPreviewName', 'loginBackgroundError')
            );
        }

        const uploadInput = document.querySelector('input[id="user_settings_background_upload"]');
        if (uploadInput) {
            uploadInput.addEventListener('change', (event) =>
                previewBackground(event, 'uploadBackgroundPreview', 'uploadBackgroundPreviewName', 'uploadBackgroundError')
            );
        }

        const downloadInput = document.querySelector('input[id="user_settings_background_download"]');
        if (downloadInput) {
            downloadInput.addEventListener('change', (event) =>
                previewBackground(event, 'downloadBackgroundPreview', 'downloadBackgroundPreviewName', 'downloadBackgroundError')
            );
        }

        const uploadTitle: HTMLInputElement | null = document.getElementById('user_settings_uploadTitle') as HTMLInputElement;
        if (uploadTitle) {
            const form_setting = document.getElementById('form_setting') as HTMLFormElement;
            const color: HTMLInputElement | null = document.getElementById('user_settings_uploadTitleColor') as HTMLInputElement;
            const fontSize: HTMLInputElement | null = document.getElementById('user_settings_uploadTitleSize') as HTMLInputElement;
            const preview: HTMLDivElement | null = document.getElementById('preview') as HTMLDivElement;
            preview.textContent = uploadTitle.value;
            preview.style.color = color.value
            preview.style.fontSize = fontSize.value + 'px'

            form_setting.addEventListener('input', function () {
                // Get form values
                const title: string = uploadTitle.value;
                const textColor: string = color.value;
                const textSize: string = fontSize.value;

                // Update preview div
                preview.textContent = title;
                preview.style.color = textColor;
                preview.style.fontSize = textSize + 'px';
            });
        }

        const logoInput = document.querySelector('input[id="user_settings_emailLogo"]');
        if (logoInput) {
            logoInput.addEventListener('change', (event) => previewLogo(event, 'logoPreview'));
        }
    });
});