import { Controller } from 'stimulus';
import Cookies from 'js-cookie';

const loader = require("./../components/loader.js");
const helper = require("./../components/helper.js");

/*
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {
    connect() {
        $(document.querySelector('.login-menu')).on('click', function(){
            $(this).toggleClass('active');
        });

        $(document.querySelector('.burger')).on('click', function(){
            $(this).toggleClass('active');
            $('.left-sidebar').toggleClass('menu-active');
        });

        loader.loadSDK('menu').then(function(webSDK) {
            webSDK.on('init', function() {
                if (this.data.user.authenticated) {
                    runWebSDK(webSDK);           
                }
            });
        })

        let runWebSDK = function (webSDK) {
            this.bonus(webSDK);
            
            if (location.pathname != '/case-history') {
                this.caseHistory(webSDK);
            }
        }.bind(this)

        this.tel().catch(error => {
            console.error('Ошибка в tel():', error);
        });
    }

    caseHistory(webSDK) {
        let countRecord = document.getElementById('countRecord');
        
        window.webSDK.loadScheduleRecList({
            st: 20170101,
            en: window.dateFormat(new Date((new Date()).getFullYear(), (new Date()).getMonth() + 6, 0)),
            start: 0,
            length: 500
        }).then(function (resolve) {
            if (countRecord) {
                if (resolve.data.length > 0) {
                    var count = 0;

                    for (var i = 0; i < resolve.data.length; i++) {
                        if (resolve.data[i].workDate >= window.dateFormat(new Date())) {
                            count++;
                        }
                    }
                    
                    countRecord.innerHTML = count;
                    if (count !== 0) {
                        countRecord.classList.remove('d-none');
                    }

                    if (location.pathname == '/') {
                        var caseHistoryWidget = document.getElementById('case-history-widget');
                            caseHistoryWidget.innerHTML = '';
                        
                        if (resolve.data.length > 0) {
                            var count = 0;
                            
                            for (var i = 0; i < resolve.data.length; i++) {
                                if (resolve.data[i].workDate >= window.dateFormat(new Date()) && count < 4) {
                                    var date = window.newDate(resolve.data[i].workDate);        
                                    var item = document.createElement('span');
                                    item.innerHTML = window.getWeekDay(date) + ', ' + window.dateFormat(date, 'd-m-Y') + ' ' + resolve.data[i].startTime;
                                    item.classList = 'line-item';
                                    caseHistoryWidget.append(item);
                                    count++;
                                }
                            }

                            if (count == 0) {
                                var item = document.createElement('span');
                                item.innerHTML = 'Записей не найдено';
                                item.classList = 'line-item empty-item';                     
                                caseHistoryWidget.append(item);    
                            }

                        } else {
                            var item = document.createElement('span');
                            item.innerHTML = 'Записей не найдено';
                            item.classList = 'line-item empty-item';                     
                            caseHistoryWidget.append(item);
                        }
                    }
                }
            }
        });
    }

    bonus() {
        var bonusWidget = document.getElementById('bonus-widget');
        var bonusMenu = document.getElementById('bonus-menu');
        
        window.webSDK.loadBonusList().then(function (resolve) {
            if (resolve.length > 0) {
                if (typeof resolve[0]['amountrub'] !== 'undefined') {
                    if (bonusMenu) {
                        bonusMenu.innerHTML = resolve[0]['amountrub'];
                        bonusMenu.classList.remove('d-none');
                    }

                    if (bonusWidget) {
                        bonusWidget.innerHTML = resolve[0]['amountrub'];   
                    }
                }
            }
        });
    }

    signOut(event) {
        if (event) {
            event.preventDefault();
        }

        const pcode = String(window?.webSDK?.data?.user?.id || '');
        const body = new URLSearchParams();
        if (pcode) {
            body.append('pcode', pcode);
        }

        fetch('/api/usrlog/logout', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            credentials: 'same-origin',
            keepalive: true,
            body: body.toString()
        }).catch(() => {
            // 
        }).finally(() => {
            window.webSDK.logout();
            window.location.href = '/logout';
        });
    }

    async tel() {
        const apiUrl = helper.getApiHostname();
        const regionId = parseInt(Cookies.get('region'));
        
        try {
            const response = await fetch(`${apiUrl}/filial/list?regionId=${regionId}`);
            if (!response.ok) {
                throw new Error(`Response status: ${response.status}`);
            }

            const result = await response.json();
            const btnCallbackClinic = document.getElementById('btn-callback-clinic');
            const phone = result.data?.[0]?.phone;

            if (!btnCallbackClinic || !phone) {
                return;
            }

            const digits = String(phone).replace(/\D/g, '');
            const normalizedDigits = digits.length === 11 && digits.startsWith('8')
                ? `7${digits.slice(1)}`
                : digits;

            const displayPhone = normalizedDigits.length === 11 && normalizedDigits.startsWith('7')
                ? `+7(${normalizedDigits.slice(1, 4)})${normalizedDigits.slice(4, 7)}-${normalizedDigits.slice(7, 9)}-${normalizedDigits.slice(9, 11)}`
                : String(phone).trim();

            // Делаем номер доступным для других частей фронта (например, карточки специалистов)
            window.clinicPhone = displayPhone;
            window.clinicPhoneRaw = normalizedDigits;

            btnCallbackClinic.innerText = displayPhone;
            btnCallbackClinic.href = normalizedDigits ? `tel:+${normalizedDigits}` : `tel:${displayPhone}`;
            
        } catch (error) {
            console.error(error.message);
        }
    }
}


