/**
 * Admin Integration Module
 * Handles external service integrations (NocoDB and Listmonk)
 */

// Initialize NocoDB links in admin panel
async function initializeNocodbLinks() {
    console.log('Starting NocoDB links initialization...');
    
    try {
        // Since we're in the admin panel, the user is already verified as admin
        // by the requireAdmin middleware. Let's get the URLs from the server directly.
        console.log('Fetching NocoDB URLs for admin panel...');
        const configResponse = await fetch('/api/admin/nocodb-urls');
        
        if (!configResponse.ok) {
            throw new Error(`NocoDB URLs fetch failed: ${configResponse.status} ${configResponse.statusText}`);
        }
        
        const config = await configResponse.json();
        console.log('NocoDB URLs received:', config);
        
        if (config.success && config.nocodbUrls) {
            console.log('Setting up NocoDB links with URLs:', config.nocodbUrls);
            
            // Set up admin dashboard NocoDB links
            setAdminNocodbLink('admin-nocodb-view-link', config.nocodbUrls.viewUrl);
            setAdminNocodbLink('admin-nocodb-login-link', config.nocodbUrls.loginSheet);
            setAdminNocodbLink('admin-nocodb-settings-link', config.nocodbUrls.settingsSheet);
            setAdminNocodbLink('admin-nocodb-shifts-link', config.nocodbUrls.shiftsSheet);
            setAdminNocodbLink('admin-nocodb-signups-link', config.nocodbUrls.shiftSignupsSheet);
            
            console.log('NocoDB links initialized in admin panel');
        } else {
            console.warn('No NocoDB URLs found in admin config response');
            // Hide the NocoDB section if no URLs are available
            const nocodbSection = document.getElementById('nocodb-links');
            const nocodbNav = document.querySelector('.admin-nav a[href="#nocodb-links"]');
            if (nocodbSection) {
                nocodbSection.style.display = 'none';
                console.log('Hidden NocoDB section');
            }
            if (nocodbNav) {
                nocodbNav.style.display = 'none';
                console.log('Hidden NocoDB nav link');
            }
        }
    } catch (error) {
        console.error('Error initializing NocoDB links in admin panel:', error);
        // Hide the NocoDB section on error
        const nocodbSection = document.getElementById('nocodb-links');
        const nocodbNav = document.querySelector('.admin-nav a[href="#nocodb-links"]');
        if (nocodbSection) {
            nocodbSection.style.display = 'none';
            console.log('Hidden NocoDB section due to error');
        }
        if (nocodbNav) {
            nocodbNav.style.display = 'none';
            console.log('Hidden NocoDB nav link due to error');
        }
    }
}

// Helper function to set admin NocoDB link href
function setAdminNocodbLink(elementId, url) {
    console.log(`Setting up NocoDB link: ${elementId} = ${url}`);
    const element = document.getElementById(elementId);
    
    if (element && url) {
        element.href = url;
        element.style.display = 'inline-flex';
        // Remove any disabled state
        element.classList.remove('btn-disabled');
        element.removeAttribute('disabled');
        console.log(`✓ Successfully set up ${elementId}`);
    } else if (element) {
        element.style.display = 'none';
        // Add disabled state if no URL
        element.classList.add('btn-disabled');
        element.setAttribute('disabled', 'disabled');
        element.href = '#';
        console.log(`⚠ Disabled ${elementId} - no URL provided`);
    } else {
        console.error(`✗ Element not found: ${elementId}`);
    }
}

// Initialize Listmonk links in admin panel
async function initializeListmonkLinks() {
    console.log('Starting Listmonk links initialization...');
    
    try {
        // Since we're in the admin panel, the user is already verified as admin
        // by the requireAdmin middleware. Let's get the URLs from the server directly.
        console.log('Fetching Listmonk URLs for admin panel...');
        const configResponse = await fetch('/api/admin/listmonk-urls');
        
        if (!configResponse.ok) {
            throw new Error(`Listmonk URLs fetch failed: ${configResponse.status} ${configResponse.statusText}`);
        }
        
        const config = await configResponse.json();
        console.log('Listmonk URLs received:', config);
        
        if (config.success && config.listmonkUrls) {
            console.log('Setting up Listmonk links with URLs:', config.listmonkUrls);
            
            // Set up admin dashboard Listmonk links
            setAdminListmonkLink('admin-listmonk-admin-link', config.listmonkUrls.adminUrl);
            setAdminListmonkLink('admin-listmonk-lists-link', config.listmonkUrls.listsUrl);
            setAdminListmonkLink('admin-listmonk-campaigns-link', config.listmonkUrls.campaignsUrl);
            setAdminListmonkLink('admin-listmonk-subscribers-link', config.listmonkUrls.subscribersUrl);
            setAdminListmonkLink('admin-listmonk-settings-link', config.listmonkUrls.settingsUrl);
            
            console.log('Listmonk links initialized in admin panel');
        } else {
            console.warn('No Listmonk URLs found in admin config response');
            // Hide the Listmonk section if no URLs are available
            const listmonkSection = document.getElementById('listmonk-links');
            const listmonkNav = document.querySelector('.admin-nav a[href="#listmonk-links"]');
            if (listmonkSection) {
                listmonkSection.style.display = 'none';
                console.log('Hidden Listmonk section');
            }
            if (listmonkNav) {
                listmonkNav.style.display = 'none';
                console.log('Hidden Listmonk nav link');
            }
        }
    } catch (error) {
        console.error('Error initializing Listmonk links in admin panel:', error);
        // Hide the Listmonk section on error
        const listmonkSection = document.getElementById('listmonk-links');
        const listmonkNav = document.querySelector('.admin-nav a[href="#listmonk-links"]');
        if (listmonkSection) {
            listmonkSection.style.display = 'none';
            console.log('Hidden Listmonk section due to error');
        }
        if (listmonkNav) {
            listmonkNav.style.display = 'none';
            console.log('Hidden Listmonk nav link due to error');
        }
    }
}

// Helper function to set admin Listmonk link href
function setAdminListmonkLink(elementId, url) {
    console.log(`Setting up Listmonk link: ${elementId} = ${url}`);
    const element = document.getElementById(elementId);
    
    if (element && url) {
        element.href = url;
        element.style.display = 'inline-flex';
        // Remove any disabled state
        element.classList.remove('btn-disabled');
        element.removeAttribute('disabled');
        console.log(`✓ Successfully set up ${elementId}`);
    } else if (element) {
        element.style.display = 'none';
        // Add disabled state if no URL
        element.classList.add('btn-disabled');
        element.setAttribute('disabled', 'disabled');
        element.href = '#';
        console.log(`⚠ Disabled ${elementId} - no URL provided`);
    } else {
        console.error(`✗ Element not found: ${elementId}`);
    }
}

// Initialize all integrations
async function initializeAllIntegrations() {
    try {
        // Initialize both integrations with a small delay to ensure DOM is ready
        await initializeNocodbLinks();
        await initializeListmonkLinks();
        console.log('All integrations initialized successfully');
    } catch (error) {
        console.error('Error initializing integrations:', error);
    }
}

// Export integration functions
window.adminIntegration = {
    initializeNocodbLinks,
    initializeListmonkLinks,
    initializeAllIntegrations,
    setAdminNocodbLink,
    setAdminListmonkLink
};
