// ======= ОБЩИЕ УТИЛИТЫ И КОНСТАНТЫ =======
const ETaxes = {
    // Константы
    PROGRESS_UPDATE_DELAY: 50,
    AUTH_POLL_INTERVAL: 6000,
    AUTH_MAX_ATTEMPTS: 20,
    
    // Глобальные переменные
    loadingDialog: null,
    cancelLoading: false,
    loadingErrors: [],
    
    // Кэш
    cache: {
        defaultLogin: null,
        cacheTime: null,
        cacheDuration: 300000 // 5 минут
    }
};

// ======= БАЗОВЫЕ УТИЛИТЫ =======
ETaxes.utils = {
    // Кэшированное получение настроек входа
    getDefaultLogin: function(callback, useCache = true) {
        const now = Date.now();
        
        if (useCache && ETaxes.cache.defaultLogin && ETaxes.cache.cacheTime && 
            (now - ETaxes.cache.cacheTime) < ETaxes.cache.cacheDuration) {
            callback(ETaxes.cache.defaultLogin);
            return;
        }
        
        frappe.call({
            method: 'invoice_az.auth.get_default_asan_login',
            callback: function(r) {
                if (r.message) {
                    ETaxes.cache.defaultLogin = r.message;
                    ETaxes.cache.cacheTime = now;
                }
                callback(r.message);
            },
            error: function() {
                callback({found: false, error: 'Network error'});
            }
        });
    },
    
    // Проверка валидности токена
    checkTokenValidity: function(callback) {
        frappe.call({
            method: 'invoice_az.auth.check_token_validity',
            callback: function(r) {
                callback(r.message && r.message.valid);
            },
            error: function() {
                callback(false);
            }
        });
    },
    
    // Форматирование валюты
    formatCurrency: function(amount) {
        return new Intl.NumberFormat('az-AZ', {
            style: 'currency',
            currency: 'AZN',
            minimumFractionDigits: 2
        }).format(amount || 0);
    },
    
    // Очистка кэша
    clearCache: function() {
        ETaxes.cache.defaultLogin = null;
        ETaxes.cache.cacheTime = null;
    }
};

// ======= ДИАЛОГИ ЗАГРУЗКИ =======
ETaxes.dialogs = {
    // Показать диалог загрузки
    showLoading: function(title, message, submessage) {
        if (ETaxes.loadingDialog) {
            this.updateLoading(title, message, submessage);
            return;
        }
        
        ETaxes.loadingDialog = new frappe.ui.Dialog({
            title: title,
            fields: [{
                fieldname: 'loading_html',
                fieldtype: 'HTML',
                options: this._getLoadingHTML(title, message, submessage)
            }],
            primary_action_label: __('Cancel'),
            primary_action: function() {
                ETaxes.cancelLoading = true;
                ETaxes.loadingDialog.$wrapper.find('.primary-action').prop('disabled', true);
                ETaxes.loadingDialog.$wrapper.find('.primary-action').html(__('Cancelling...'));
                $('#status_message p').text(__('Cancelling the operation.'));
            }
        });
        
        ETaxes.cancelLoading = false;
        ETaxes.loadingDialog.show();
        ETaxes.loadingDialog.$wrapper.find('.modal-dialog').css('max-width', '450px');
    },
    
    // Обновить сообщение в диалоге
    updateLoading: function(title, message, submessage) {
        if (!ETaxes.loadingDialog) return;
        
        if (title) $('#loading_title').text(title);
        if (message) $('#loading_message').text(message);
        if (submessage !== undefined) {
            $('#loading_submessage').text(submessage);
            $('#loading_submessage').toggle(!!submessage);
        }
    },
    
    // Показать код верификации
    showVerificationCode: function(code) {
        if (ETaxes.loadingDialog && code) {
            $('#verification_code').text(code);
            $('#verification_code_container').show();
        }
    },
    
    // Установить статус успеха
    setSuccess: function(message, submessage, callback, delay = 2000) {
        if (!ETaxes.loadingDialog) {
            if (callback) callback();
            return;
        }
        
        ETaxes.loadingDialog.$wrapper.find('.loading-animation').html(`
            <div style="width: 64px; height: 64px; display: flex; align-items: center; justify-content: center;">
                <i class="fa fa-check" style="font-size: 48px; color: #5cb85c;"></i>
            </div>
        `);
        
        $('#loading_message').text(message);
        if (submessage !== undefined) {
            $('#loading_submessage').text(submessage);
            $('#loading_submessage').toggle(!!submessage);
        }
        
        $('#verification_code_container').hide();
        ETaxes.loadingDialog.set_primary_action(null);
        ETaxes.loadingDialog.set_secondary_action(null);
        
        setTimeout(() => {
            this.hide();
            if (callback) callback();
        }, delay);
    },
    
    // Установить статус ошибки
    setError: function(message, submessage, showCloseButton = true) {
        if (!ETaxes.loadingDialog) return;

        // Update dialog title
        ETaxes.loadingDialog.set_title(__('Error'));

        // Change animation to error icon
        ETaxes.loadingDialog.$wrapper.find('.loading-animation').html(`
            <div style="width: 64px; height: 64px; display: flex; align-items: center; justify-content: center;">
                <i class="fa fa-times" style="font-size: 48px; color: #d9534f;"></i>
            </div>
        `);

        // Clear all existing text elements
        ETaxes.loadingDialog.$wrapper.find('#loading_title').text('');
        ETaxes.loadingDialog.$wrapper.find('#loading_submessage').remove();

        // Set error message
        const $msgElement = ETaxes.loadingDialog.$wrapper.find('#loading_message');
        if ($msgElement.length) {
            $msgElement.css({
                'color': '#d9534f',
                'font-weight': '500',
                'font-size': '14px',
                'margin-top': '15px'
            });

            if (submessage) {
                $msgElement.html(submessage.replace(/\n/g, '<br>'));
            } else {
                $msgElement.text(message);
            }
        }

        $('#verification_code_container').hide();
        
        if (showCloseButton) {
            ETaxes.loadingDialog.set_primary_action(__('Close'), () => this.hide());
        }
    },
    
    // Скрыть диалог
    hide: function() {
        if (ETaxes.loadingDialog) {
            try {
                ETaxes.loadingDialog.hide();
            } catch (e) {
                console.error("Error hiding loading dialog:", e);
            }
            ETaxes.loadingDialog = null;
        }
        ETaxes.cancelLoading = false;
    },
    
    // Получить HTML для диалога загрузки
    _getLoadingHTML: function(title, message, submessage) {
        return `
            <div class="text-center">
                <div class="loading-animation" style="display: inline-block; width: 64px; height: 64px;">
                    <div style="width: 64px; height: 64px; border: 6px solid #4e73df; border-radius: 50%; border-color: #4e73df transparent #4e73df transparent; animation: lds-dual-ring 1.2s linear infinite;"></div>
                </div>
                <style>
                    @keyframes lds-dual-ring {
                        0% { transform: rotate(0deg); }
                        100% { transform: rotate(360deg); }
                    }
                </style>
                <div class="mt-3" id="status_message">
                    <h4 id="loading_title">${title || __('Please wait...')}</h4>
                    <p id="loading_message">${message || __('The operation may take some time')}</p>
                    <p id="loading_submessage" style="${submessage ? '' : 'display:none'}">${submessage || ''}</p>
                </div>
                <div id="verification_code_container" style="display:none; margin-top: 15px;">
                    <div style="background: #f8f9fa; padding: 10px; display: inline-block; border-radius: 5px; font-size: 24px; font-weight: bold; letter-spacing: 2px; color: #333; border: 1px solid #ddd;">
                        <span id="verification_code">----</span>
                    </div>
                    <p style="margin-top: 5px; font-size: 12px; color: #666;">Verification Code</p>
                </div>
            </div>
        `;
    }
};

// ======= МОДУЛЬ АУТЕНТИФИКАЦИИ =======
ETaxes.auth = {
    // Проверить токен и обработать аутентификацию при необходимости
    checkAndProcess: function(callback) {
        ETaxes.utils.checkTokenValidity(function(isValid) {
            if (isValid) {
                callback();
            } else {
                frappe.confirm(
                    __('Your E-Taxes session has expired or authentication is required. Would you like to authenticate now?'),
                    function() {
                        ETaxes.auth.startProcess(callback);
                    },
                    function() {
                        frappe.show_alert({
                            message: __('Authentication canceled. Operation cannot be completed.'),
                            indicator: 'red'
                        }, 5);
                    }
                );
            }
        });
    },
    
    // Начать процесс аутентификации
    startProcess: function(callback) {
        ETaxes.dialogs.showLoading(
            __('Starting Authentication'),
            __('Getting Asan Login settings...'),
            __('Please wait')
        );
        
        ETaxes.utils.getDefaultLogin(function(loginData) {
            if (loginData && loginData.found) {
                const asanLoginName = loginData.name;
                ETaxes.dialogs.updateLoading(
                    null,
                    __('Sending authentication request...'),
                    __('This will send a request to your Asan Imza mobile app')
                );
                
                frappe.call({
                    method: 'invoice_az.auth.handle_authentication',
                    args: { 'asan_login_name': asanLoginName },
                    callback: function(r) {
                        if (r.message && r.message.success) {
                            const bearerToken = r.message.bearer_token;
                            
                            if (r.message.verification_code) {
                                ETaxes.dialogs.showVerificationCode(r.message.verification_code);
                            }
                            
                            ETaxes.dialogs.updateLoading(
                                null,
                                __('Waiting for confirmation on your phone'),
                                __('Please check your phone and confirm the authentication request')
                            );
                            
                            ETaxes.auth.pollStatus(asanLoginName, bearerToken, function(success) {
                                if (success) {
                                    ETaxes.auth.complete(asanLoginName, callback);
                                } else {
                                    ETaxes.dialogs.setError(
                                        __('Authentication Failed'),
                                        __('Could not authenticate with Asan Imza')
                                    );
                                }
                            });
                        } else {
                            ETaxes.dialogs.setError(
                                __('Authentication Error'),
                                r.message ? r.message.message : __('Authentication request failed')
                            );
                        }
                    }
                });
            } else {
                ETaxes.dialogs.setError(
                    __('No Asan Login Settings'),
                    __('Please configure Asan Login settings first')
                );
            }
        }, false); // Не использовать кэш для аутентификации
    },
    
    // Опрос статуса аутентификации
    pollStatus: function(asanLoginName, bearerToken, callback) {
        let attempts = 0;
        let stopPolling = false;
        
        function pollStatusStep() {
            if (attempts >= ETaxes.AUTH_MAX_ATTEMPTS || stopPolling) {
                if (attempts >= ETaxes.AUTH_MAX_ATTEMPTS) {
                    ETaxes.dialogs.setError(
                        __('Authentication Timeout'),
                        __('The authentication request has timed out. Please try again.')
                    );
                    callback(false);
                }
                return;
            }
            
            attempts++;
            
            ETaxes.dialogs.updateLoading(
                null,
                __('Waiting for confirmation on your phone'),
                __('Please check your phone and confirm the authentication request') + 
                ' (' + attempts + '/' + ETaxes.AUTH_MAX_ATTEMPTS + ')'
            );
            
            frappe.call({
                method: 'invoice_az.auth.poll_auth_status',
                args: {
                    'asan_login_name': asanLoginName,
                    'bearer_token': bearerToken
                },
                callback: function(r) {
                    if (r.message && r.message.success) {
                        if (r.message.authenticated) {
                            stopPolling = true;
                            ETaxes.dialogs.setSuccess(
                                __('Authentication Successful'),
                                __('You are now authenticated with Asan Imza'),
                                function() {
                                    callback(true);
                                }
                            );
                        } else {
                            setTimeout(pollStatusStep, ETaxes.AUTH_POLL_INTERVAL);
                        }
                    } else {
                        stopPolling = true;
                        ETaxes.dialogs.setError(
                            __('Authentication Error'),
                            r.message ? r.message.message : __('An unknown error occurred')
                        );
                        callback(false);
                    }
                },
                error: function(err) {
                    console.error('Error during status check:', err);
                    setTimeout(pollStatusStep, ETaxes.AUTH_POLL_INTERVAL);
                }
            });
        }
        
        pollStatusStep();
    },
    
    // Завершение аутентификации
    complete: function(asanLoginName, callback) {
        ETaxes.dialogs.showLoading(
            __('Completing Authentication'),
            __('Getting certificates...'),
            __('Please wait')
        );
        
        frappe.call({
            method: 'invoice_az.auth.get_auth_certificates',
            args: { 'asan_login_name': asanLoginName },
            callback: function(certR) {
                if (certR.message && certR.message.success) {
                    ETaxes.dialogs.updateLoading(
                        null,
                        __('Certificates retrieved'),
                        __('Selecting certificate and taxpayer')
                    );
                    
                    frappe.call({
                        method: 'frappe.client.get',
                        args: {
                            doctype: 'Asan Login',
                            name: asanLoginName
                        },
                        callback: function(r) {
                            if (r.message && r.message.selected_certificate_json) {
                                try {
                                    const certData = JSON.parse(r.message.selected_certificate_json);
                                    const certName = r.message.selected_certificate;
                                    
                                    ETaxes.dialogs.updateLoading(
                                        null,
                                        __('Selecting certificate'),
                                        certName
                                    );
                                    
                                    ETaxes.auth._selectCertificate(asanLoginName, certData, certName, callback);
                                } catch (e) {
                                    console.error('Error parsing certificate:', e);
                                    ETaxes.dialogs.hide();
                                    ETaxes.auth._showCertificateSelector(certR.message.certificates, asanLoginName, callback);
                                }
                            } else {
                                ETaxes.dialogs.hide();
                                ETaxes.auth._showCertificateSelector(certR.message.certificates, asanLoginName, callback);
                            }
                        }
                    });
                } else {
                    ETaxes.dialogs.setError(
                        __('Error'),
                        certR.message ? certR.message.message : __('Failed to get certificates')
                    );
                }
            }
        });
    },
    
    // Выбор сертификата
    _selectCertificate: function(asanLoginName, certData, certName, callback) {
        frappe.call({
            method: 'invoice_az.auth.select_certificate',
            args: {
                'asan_login_name': asanLoginName,
                'certificate_data': certData,
                'certificate_name': certName
            },
            callback: function(r) {
                if (r.message && r.message.success) {
                    ETaxes.dialogs.updateLoading(
                        null,
                        __('Selecting taxpayer'),
                        __('Using certificate: ') + certName
                    );
                    
                    frappe.call({
                        method: 'invoice_az.auth.select_taxpayer',
                        args: { 'asan_login_name': asanLoginName },
                        callback: function(r) {
                            if (r.message && r.message.success) {
                                ETaxes.utils.clearCache(); // Очищаем кэш после успешной аутентификации
                                ETaxes.dialogs.setSuccess(
                                    __('Authentication Complete'),
                                    __('You can now access E-Taxes services'),
                                    callback
                                );
                            } else {
                                ETaxes.dialogs.setError(
                                    __('Error'),
                                    r.message ? r.message.message : __('Failed to select taxpayer')
                                );
                            }
                        }
                    });
                } else {
                    ETaxes.dialogs.setError(
                        __('Error'),
                        r.message ? r.message.message : __('Failed to select certificate')
                    );
                }
            }
        });
    },
    
    // Показать селектор сертификатов
    _showCertificateSelector: function(certificates, asanLoginName, callback) {
        if (!certificates || !certificates.length) {
            frappe.msgprint(__('No certificates available'));
            return;
        }
        
        let certHtml = '<div style="max-height: 400px; overflow-y: auto;"><table class="table table-bordered">';
        certHtml += '<thead><tr><th>Type</th><th>Name</th><th>ID</th><th>Position</th><th>Status</th><th></th></tr></thead><tbody>';
        
        certificates.forEach(function(cert, index) {
            let name = '';
            let id = '';
            
            if (cert.taxpayerType === 'individual' && cert.individualInfo) {
                name = cert.individualInfo.name || '';
                id = cert.individualInfo.fin || '';
            } else if (cert.legalInfo) {
                name = cert.legalInfo.name || '';
                id = cert.legalInfo.tin || cert.legalInfo.voen || '';
            }
            
            certHtml += '<tr>' +
                '<td>' + (cert.taxpayerType || '') + '</td>' +
                '<td>' + name + '</td>' +
                '<td>' + id + '</td>' +
                '<td>' + (cert.position || '') + '</td>' +
                '<td>' + (cert.hasAccess ? 'Active' : 'Inactive') + (cert.liquidated ? ' (Liquidated)' : '') + '</td>' +
                '<td><button class="btn btn-xs btn-primary select-cert" data-index="' + index + '">Select</button></td>' +
                '</tr>';
        });
        
        certHtml += '</tbody></table></div>';
        
        const dialog = new frappe.ui.Dialog({
            title: __('Select Certificate'),
            fields: [{
                fieldtype: 'HTML',
                fieldname: 'certificates',
                options: certHtml
            }]
        });
        
        dialog.show();
        
        dialog.$wrapper.find('.select-cert').on('click', function() {
            const index = $(this).data('index');
            const cert = certificates[index];
            
            let certName = '';
            if (cert.taxpayerType === 'individual' && cert.individualInfo) {
                certName = `${cert.individualInfo.name} (${cert.individualInfo.fin})`;
            } else if (cert.legalInfo) {
                certName = `${cert.legalInfo.name} (${cert.legalInfo.voen || cert.legalInfo.tin})`;
            } else {
                certName = `Certificate ${index + 1}`;
            }
            
            dialog.hide();
            
            ETaxes.dialogs.showLoading(
                __('Selecting Certificate'),
                __('Processing your selection...'),
                certName
            );
            
            ETaxes.auth._selectCertificate(asanLoginName, cert, certName, callback);
        });
    }
};
/**
 * Supplier Form Configuration
 * E-Taxes integration for Individual suppliers
 */

frappe.ui.form.on('Supplier', {
    refresh: function(frm) {
        // Add event handler for fetch button
        if (frm.doc.supplier_type === 'Individual' && frm.doc.fin && frm.doc.passport_serial_number) {
            setup_fetch_button_handler(frm);
        }
    },

    // Re-setup button when supplier type changes
    supplier_type: function(frm) {
        if (frm.doc.supplier_type === 'Individual' && frm.doc.fin && frm.doc.passport_serial_number) {
            setup_fetch_button_handler(frm);
        }
    },

    // Re-setup button when FIN changes
    fin: function(frm) {
        if (frm.doc.supplier_type === 'Individual' && frm.doc.fin && frm.doc.passport_serial_number) {
            setup_fetch_button_handler(frm);
        }
    },

    // Re-setup button when Passport changes
    passport_serial_number: function(frm) {
        if (frm.doc.supplier_type === 'Individual' && frm.doc.fin && frm.doc.passport_serial_number) {
            setup_fetch_button_handler(frm);
        }
    }
});

/**
 * Setup click handler for fetch button inside the section
 */
function setup_fetch_button_handler(frm) {
    // Wait for DOM to be ready
    setTimeout(function() {
        $('#fetch-from-etaxes-btn').off('click').on('click', function() {
            fetch_supplier_data_from_etaxes(frm);
        });
    }, 200);
}

/**
 * Fetch and auto-fill supplier data from E-Taxes
 */
function fetch_supplier_data_from_etaxes(frm) {
    // Check authentication first (same pattern as Sales Invoice)
    ETaxes.auth.checkAndProcess(function() {
        execute_fetch_supplier_data(frm);
    });
}

/**
 * Execute the actual fetch operation
 */
function execute_fetch_supplier_data(frm) {
    // Show confirmation dialog
    frappe.confirm(
        __('Fetch supplier data from E-Taxes?') + '<br><br>' +
        __('FIN: {0}', [frm.doc.fin]) + '<br>' +
        __('Passport: {0}', [frm.doc.passport_serial_number]) + '<br><br>' +
        __('This will automatically fill the following fields if they are empty:') + '<br>' +
        __('- Date of Birth') + '<br>' +
        __('- First Name') + '<br>' +
        __('- Last Name') + '<br>' +
        __('- Phone Number') + '<br>' +
        __('- Supplier Name (Full Name)'),
        function() {
            // Show loading
            frappe.show_alert({
                message: __('Fetching data from E-Taxes...'),
                indicator: 'blue'
            }, 5);

            // Make API call
            frappe.call({
                method: 'invoice_az.supplier_api.update_supplier_from_etaxes',
                args: {
                    supplier_name: frm.doc.name
                },
                callback: function(r) {
                    if (r.message && r.message.success) {
                        // Success
                        frappe.show_alert({
                            message: __('Supplier data fetched successfully!') + '<br>' +
                                    r.message.message,
                            indicator: 'green'
                        }, 7);

                        // Reload document to show updated fields
                        frm.reload_doc();
                    } else {
                        // Error
                        const errorMsg = r.message ? r.message.message : __('Failed to fetch supplier data from E-Taxes');
                        frappe.msgprint({
                            title: __('Error'),
                            indicator: 'red',
                            message: errorMsg
                        });
                    }
                },
                error: function(r) {
                    frappe.msgprint({
                        title: __('Error'),
                        indicator: 'red',
                        message: __('Failed to communicate with E-Taxes service.')
                    });
                }
            });
        }
    );
}
