export function onLoad() {
    if (localStorage.getItem('action') == null) {
        window.location.href = '/';
    }
    if (localStorage.getItem('institut') == null) {
        window.location.href = '/chooseinstitut';
    }
    
    // Подготовка поля ввода номера телефона
    document.getElementById('phoneNumberInput').addEventListener('input', function (e) {
        e.target.value = e.target.value.replace(/\D/g, '').slice(0, 10); // Limit to 10 digits
        let num = e.target.value;
        if (num.length > 3 && num.length <= 6) {
            e.target.value = num.substring(0, 3) + ' ' + num.substring(3, 6);
        } else if (num.length > 6 && num.length <= 8) {
            e.target.value = num.substring(0, 3) + ' ' + num.substring(3, 6) + ' ' + num.substring(6, 8);
        } else if (num.length > 8) {
            e.target.value = num.substring(0, 3) + ' ' + num.substring(3, 6) + ' ' + num.substring(6, 10);
        }
    });

    const specialitySelect = document.getElementById('speciality');
    const continueButton = document.querySelector('a[href="/statement"]');
    const options = document.querySelectorAll('input[name="options"]');
    const kursElements = document.querySelectorAll('input[name="kurs"]');
    const phoneNumberInput = document.getElementById('phoneNumberInput');
    const checkboxPaid = document.getElementById('paidCheckbox');
    const checkboxOchno = document.getElementById('ochnoCheckbox');

    const kursElement2 = Array.from(kursElements).find(k => k.getAttribute('aria-label') === '2');
    const kursElement3 = Array.from(kursElements).find(k => k.getAttribute('aria-label') === '3');
    const kursElement4 = Array.from(kursElements).find(k => k.getAttribute('aria-label') === '4');
    const kursElement5 = Array.from(kursElements).find(k => k.getAttribute('aria-label') === '5');

    fetch('/api/getSpecialities?institutId=' + localStorage.getItem('institut'))
        .then(response => response.json())
        .then(data => {
            const specialities = data.filter(speciality => speciality.name === 'Программная инженерия');
            const otherSpecialities = data.filter(speciality => speciality.name !== 'Программная инженерия');

            specialities.concat(otherSpecialities).forEach(speciality => {
                const option = document.createElement('option');
                option.value = speciality.id;
                option.text = speciality.code + " " + (speciality.name.includes('Программная инженерия') ? '🏆 ' + speciality.name : speciality.name);
                specialitySelect.add(option);
            });

            let specialityData = localStorage.getItem('speciality');
            if (specialityData) {
                specialitySelect.value = specialityData;
            }
            validateForm();
        });
    
    // Загрузка данных из хранилища если данные есть
    function loadFromLocalStorage() {
        const phoneNumber = localStorage.getItem('phoneNumber');
        const paid = localStorage.getItem('paid');
        const ochno = localStorage.getItem('ochno');
        const option = localStorage.getItem('option');
        const kurs = localStorage.getItem('kurs');

        if (phoneNumber) {
            phoneNumberInput.value = phoneNumber;
        }

        if (paid) {
            checkboxPaid.checked = paid === "true";
        }

        if (ochno) {
            checkboxOchno.checked = ochno === "false";
        }

        if (option) {
            const optionElement = Array.from(options).find(optionElement => optionElement.getAttribute('aria-label') === option);
            if (optionElement) {
                optionElement.checked = true;
            }
        }

        if (kurs) {
            const kursElement = Array.from(kursElements).find(kursElement => kursElement.getAttribute('aria-label') === kurs);
            if (kursElement) {
                kursElement.checked = true;
            }
        }
    }

    function validateForm() {
        const isOptionSelected = Array.from(options).some(option => option.checked);
        const isKursSelected = Array.from(kursElements).some(k => k.checked);
        const isPhoneNumberValid = phoneNumberInput.value.length === 12;

        // Блокировка курсов в зависимости от выбранного типа обучения
        if (isOptionSelected) {
            var typeOfEducation = (Array.from(options).find(option => option.checked).getAttribute('aria-label'));
            if (typeOfEducation === "Баклан") {
                kursElement3.disabled = false;
                kursElement4.disabled = false;
                kursElement5.disabled = true;

                if (kursElement5.checked) {
                    kursElement5.checked = false;
                    kursElement4.checked = true;
                }

            } else if (typeOfEducation === "Маг") {
                kursElement3.disabled = true;
                kursElement4.disabled = true;
                kursElement5.disabled = true;

                if (kursElement5.checked || kursElement4.checked || kursElement3.checked) {
                    kursElement5.checked = false;
                    kursElement4.checked = false;
                    kursElement3.checked = false;
                    kursElement2.checked = true;
                }
            } else if (typeOfEducation === "Спец") {
                kursElement3.disabled = false;
                kursElement4.disabled = false;
                kursElement5.disabled = false;
            }
        }
        
        if (isOptionSelected && isKursSelected && isPhoneNumberValid && specialitySelect.value !== '0') {
            continueButton.classList.remove('btn-disabled');
            localStorage.setItem('phoneNumber', phoneNumberInput.value);
            localStorage.setItem('paid', checkboxPaid.checked);
            localStorage.setItem('ochno', !checkboxOchno.checked);
            localStorage.setItem('option', typeOfEducation);
            localStorage.setItem('kurs', Array.from(kursElements).find(k => k.checked).getAttribute('aria-label'));
            localStorage.setItem('speciality', specialitySelect.value);
        } else {
            continueButton.classList.add('btn-disabled');
        }
    }

    loadFromLocalStorage();

    options.forEach(option => option.addEventListener('change', validateForm));
    kursElements.forEach(k => k.addEventListener('change', validateForm));
    phoneNumberInput.addEventListener('input', validateForm);
    checkboxPaid.addEventListener('change', validateForm);
    checkboxOchno.addEventListener('change', validateForm);
    specialitySelect.addEventListener('change', validateForm);

    validateForm();
}