const { chromium } = require('playwright');

/**
 * Test Edit Event Page Functionality
 * 
 * Tests both error handling when no event_id and proper loading with event_id
 */

class EditEventPageTester {
    constructor(baseUrl = 'https://upskill-staging.measurequick.com') {
        this.baseUrl = baseUrl;
        this.browser = null;
        this.page = null;
        this.testResults = [];
    }

    async init() {
        console.log('🚀 Initializing Edit Event Page Tester...');
        this.browser = await chromium.launch({ 
            headless: true,
            args: ['--no-sandbox', '--disable-setuid-sandbox']
        });
        this.page = await this.browser.newPage();
        
        // Set viewport for consistent testing
        await this.page.setViewportSize({ width: 1280, height: 720 });
        
        console.log('✅ Browser initialized');
    }

    async login() {
        console.log('\n📝 Logging in as test trainer...');
        
        try {
            await this.page.goto(`${this.baseUrl}/training-login/`);
            await this.page.waitForSelector('input[name="log"]', { timeout: 10000 });
            
            // Fill login form
            await this.page.fill('input[name="log"]', 'test_trainer');
            await this.page.fill('input[name="pwd"]', 'TestTrainer123!');
            
            // Submit login
            await this.page.click('input[type="submit"]');
            
            // Wait for redirect to dashboard
            await this.page.waitForURL('**/trainer/dashboard/**', { timeout: 15000 });
            
            console.log('✅ Login successful');
            return true;
        } catch (error) {
            console.error('❌ Login failed:', error.message);
            return false;
        }
    }

    async testEditEventPageWithoutEventId() {
        console.log('\n🧪 Testing Edit Event Page without event_id parameter...');
        
        try {
            // Navigate to edit-event page without event_id
            await this.page.goto(`${this.baseUrl}/trainer/edit-event/`);
            await this.page.waitForLoadState('networkidle');
            
            // Check if page loads
            const title = await this.page.textContent('h1');
            const isCorrectTitle = title && title.includes('Edit Event');
            
            // Check for error message
            const errorNotice = await this.page.locator('.hvac-error-notice').first();
            const hasErrorNotice = await errorNotice.isVisible();
            
            // Check error message content
            let errorMessage = '';
            if (hasErrorNotice) {
                errorMessage = await errorNotice.textContent();
            }
            
            // Check for "Back to Event Management" link
            const backLink = await this.page.locator('a[href*="/trainer/event/manage/"]').first();
            const hasBackLink = await backLink.isVisible();
            
            // Check navigation menu is present
            const navMenu = await this.page.locator('.hvac-trainer-navigation, .hvac-nav-menu').first();
            const hasNavigation = await navMenu.isVisible();
            
            const result = {
                test: 'Edit Event Page Without event_id',
                status: isCorrectTitle && hasErrorNotice && hasBackLink ? 'PASS' : 'FAIL',
                details: {
                    correctTitle: isCorrectTitle,
                    hasErrorNotice: hasErrorNotice,
                    errorMessage: errorMessage.trim(),
                    hasBackLink: hasBackLink,
                    hasNavigation: hasNavigation,
                    pageUrl: this.page.url()
                }
            };
            
            this.testResults.push(result);
            console.log(`${result.status === 'PASS' ? '✅' : '❌'} ${result.test}: ${result.status}`);
            console.log(`   Error Notice: ${hasErrorNotice ? 'Present' : 'Missing'}`);
            console.log(`   Error Message: "${errorMessage.trim()}"`);
            console.log(`   Back Link: ${hasBackLink ? 'Present' : 'Missing'}`);
            
            return result.status === 'PASS';
        } catch (error) {
            console.error('❌ Test failed:', error.message);
            this.testResults.push({
                test: 'Edit Event Page Without event_id',
                status: 'ERROR',
                error: error.message
            });
            return false;
        }
    }

    async findExistingEvent() {
        console.log('\n🔍 Finding existing event for testing...');
        
        try {
            // Navigate to event management page
            await this.page.goto(`${this.baseUrl}/trainer/event/manage/`);
            await this.page.waitForLoadState('networkidle');
            
            // Look for event management links or existing events
            const eventLinks = await this.page.locator('a[href*="event_id="], a[href*="/edit-event/"]').all();
            
            if (eventLinks.length > 0) {
                // Extract event ID from first available edit link
                const href = await eventLinks[0].getAttribute('href');
                const eventIdMatch = href.match(/event_id=(\d+)/);
                
                if (eventIdMatch) {
                    const eventId = eventIdMatch[1];
                    console.log(`✅ Found existing event ID: ${eventId}`);
                    return eventId;
                }
            }
            
            // If no events found, check if there are any events in the system
            console.log('⚠️  No existing events found via edit links');
            
            // Try to find events using tribe events
            const tribeEvents = await this.page.evaluate(() => {
                // Look for any event data in the page
                const eventElements = document.querySelectorAll('[data-event-id], .tribe-events-event');
                const eventIds = [];
                
                eventElements.forEach(el => {
                    const eventId = el.getAttribute('data-event-id') || 
                                   el.getAttribute('data-event') ||
                                   el.id.match(/event-(\d+)/)?.[1];
                    if (eventId) {
                        eventIds.push(eventId);
                    }
                });
                
                return eventIds;
            });
            
            if (tribeEvents.length > 0) {
                console.log(`✅ Found event ID from page data: ${tribeEvents[0]}`);
                return tribeEvents[0];
            }
            
            // If still no events, return a test event ID
            console.log('⚠️  No events found, using test event ID: 1');
            return '1';
            
        } catch (error) {
            console.error('❌ Error finding existing event:', error.message);
            return '1'; // Fallback to test ID
        }
    }

    async testEditEventPageWithEventId(eventId) {
        console.log(`\n🧪 Testing Edit Event Page with event_id=${eventId}...`);
        
        try {
            // Navigate to edit-event page with event_id
            await this.page.goto(`${this.baseUrl}/trainer/edit-event/?event_id=${eventId}`);
            await this.page.waitForLoadState('networkidle');
            
            // Check if page loads
            const title = await this.page.textContent('h1');
            const isCorrectTitle = title && title.includes('Edit Event');
            
            // Check for info notice (should show event ID being edited)
            const infoNotice = await this.page.locator('.hvac-form-notice').first();
            const hasInfoNotice = await infoNotice.isVisible();
            
            // Check info message content
            let infoMessage = '';
            if (hasInfoNotice) {
                infoMessage = await infoNotice.textContent();
            }
            
            // Check if REST API script variable is set
            const restApiVariable = await this.page.evaluate(() => {
                return typeof window.hvacEditEventId !== 'undefined' ? window.hvacEditEventId : null;
            });
            
            // Check if TEC edit form is loaded
            const tecForm = await this.page.locator('form, .tribe-community-events, .tribe-events').first();
            const hasTecForm = await tecForm.isVisible();
            
            // Check navigation menu is present
            const navMenu = await this.page.locator('.hvac-trainer-navigation, .hvac-nav-menu').first();
            const hasNavigation = await navMenu.isVisible();
            
            // Check console messages for REST API initialization
            const consoleLogs = await this.page.evaluate(() => {
                return window.console._logs || [];
            });
            
            const result = {
                test: `Edit Event Page With event_id=${eventId}`,
                status: isCorrectTitle && hasInfoNotice ? 'PASS' : 'FAIL',
                details: {
                    correctTitle: isCorrectTitle,
                    hasInfoNotice: hasInfoNotice,
                    infoMessage: infoMessage.trim(),
                    restApiVariable: restApiVariable,
                    hasTecForm: hasTecForm,
                    hasNavigation: hasNavigation,
                    pageUrl: this.page.url(),
                    eventId: eventId
                }
            };
            
            this.testResults.push(result);
            console.log(`${result.status === 'PASS' ? '✅' : '❌'} ${result.test}: ${result.status}`);
            console.log(`   Info Notice: ${hasInfoNotice ? 'Present' : 'Missing'}`);
            console.log(`   Info Message: "${infoMessage.trim()}"`);
            console.log(`   REST API Variable: ${restApiVariable || 'Not Set'}`);
            console.log(`   TEC Form: ${hasTecForm ? 'Present' : 'Missing'}`);
            
            return result.status === 'PASS';
        } catch (error) {
            console.error('❌ Test failed:', error.message);
            this.testResults.push({
                test: `Edit Event Page With event_id=${eventId}`,
                status: 'ERROR',
                error: error.message
            });
            return false;
        }
    }

    async checkTecCommunityEventsPlugin() {
        console.log('\n🔌 Checking TEC Community Events Plugin status...');
        
        try {
            // Check for TEC Community Events plugin indicators
            const tecIndicators = await this.page.evaluate(() => {
                // Check for TEC script files
                const tecScripts = Array.from(document.querySelectorAll('script[src*="community-events"]')).length;
                
                // Check for TEC CSS files
                const tecStyles = Array.from(document.querySelectorAll('link[href*="community-events"]')).length;
                
                // Check for TEC body classes
                const bodyClasses = document.body.className;
                const hasTecClasses = bodyClasses.includes('tribe') || bodyClasses.includes('community-events');
                
                // Check for global TEC variables
                const tecVars = typeof tribe_community_events !== 'undefined' || 
                               typeof tribe !== 'undefined' ||
                               typeof TribeCommunityEvents !== 'undefined';
                
                return {
                    tecScripts: tecScripts,
                    tecStyles: tecStyles,
                    hasTecClasses: hasTecClasses,
                    tecVars: tecVars
                };
            });
            
            const isActive = tecIndicators.tecScripts > 0 || 
                           tecIndicators.tecStyles > 0 || 
                           tecIndicators.hasTecClasses || 
                           tecIndicators.tecVars;
            
            const result = {
                test: 'TEC Community Events Plugin Check',
                status: isActive ? 'ACTIVE' : 'INACTIVE',
                details: tecIndicators
            };
            
            this.testResults.push(result);
            console.log(`${isActive ? '✅' : '⚠️'} TEC Community Events Plugin: ${result.status}`);
            console.log(`   Scripts: ${tecIndicators.tecScripts}`);
            console.log(`   Styles: ${tecIndicators.tecStyles}`);
            console.log(`   Body Classes: ${tecIndicators.hasTecClasses ? 'Present' : 'Missing'}`);
            console.log(`   Variables: ${tecIndicators.tecVars ? 'Present' : 'Missing'}`);
            
            return isActive;
        } catch (error) {
            console.error('❌ Plugin check failed:', error.message);
            this.testResults.push({
                test: 'TEC Community Events Plugin Check',
                status: 'ERROR',
                error: error.message
            });
            return false;
        }
    }

    async takeScreenshot(name) {
        try {
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            const filename = `/tmp/playwright-mcp-output/2025-08-12T10-37-16.007Z/edit-event-${name}-${timestamp}.png`;
            await this.page.screenshot({ path: filename, fullPage: true });
            console.log(`📸 Screenshot saved: ${filename}`);
            return filename;
        } catch (error) {
            console.error('❌ Screenshot failed:', error.message);
            return null;
        }
    }

    async generateReport() {
        console.log('\n📊 Test Results Summary:');
        console.log('='.repeat(50));
        
        let passCount = 0;
        let failCount = 0;
        let errorCount = 0;
        
        this.testResults.forEach((result, index) => {
            console.log(`\n${index + 1}. ${result.test}`);
            console.log(`   Status: ${result.status}`);
            
            if (result.status === 'PASS') passCount++;
            else if (result.status === 'FAIL') failCount++;
            else errorCount++;
            
            if (result.details) {
                Object.entries(result.details).forEach(([key, value]) => {
                    console.log(`   ${key}: ${value}`);
                });
            }
            
            if (result.error) {
                console.log(`   Error: ${result.error}`);
            }
        });
        
        console.log('\n📈 Summary:');
        console.log(`   ✅ Passed: ${passCount}`);
        console.log(`   ❌ Failed: ${failCount}`);
        console.log(`   🔥 Errors: ${errorCount}`);
        console.log(`   📊 Total: ${this.testResults.length}`);
        
        const successRate = Math.round((passCount / this.testResults.length) * 100);
        console.log(`   🎯 Success Rate: ${successRate}%`);
        
        return {
            passed: passCount,
            failed: failCount,
            errors: errorCount,
            total: this.testResults.length,
            successRate: successRate,
            results: this.testResults
        };
    }

    async cleanup() {
        if (this.browser) {
            await this.browser.close();
            console.log('🧹 Browser closed');
        }
    }

    async runAllTests() {
        try {
            await this.init();
            
            // Login first
            const loginSuccess = await this.login();
            if (!loginSuccess) {
                throw new Error('Login failed - cannot proceed with tests');
            }
            
            // Test 1: Edit event page without event_id (should show error)
            await this.testEditEventPageWithoutEventId();
            await this.takeScreenshot('without-event-id');
            
            // Test 2: Check TEC plugin status
            await this.checkTecCommunityEventsPlugin();
            
            // Test 3: Find existing event and test with event_id
            const eventId = await this.findExistingEvent();
            await this.testEditEventPageWithEventId(eventId);
            await this.takeScreenshot('with-event-id');
            
            // Generate final report
            const report = await this.generateReport();
            
            return report;
            
        } catch (error) {
            console.error('❌ Test suite failed:', error.message);
            throw error;
        } finally {
            await this.cleanup();
        }
    }
}

// Run tests if called directly
if (require.main === module) {
    const tester = new EditEventPageTester();
    
    tester.runAllTests()
        .then(report => {
            console.log('\n🎉 Test suite completed successfully!');
            process.exit(report.failed === 0 && report.errors === 0 ? 0 : 1);
        })
        .catch(error => {
            console.error('\n💥 Test suite failed:', error.message);
            process.exit(1);
        });
}

module.exports = EditEventPageTester;