import { test, expect } from '@playwright/test';
import { CommonActions } from './utils/common-actions';

/**
 * Working Master Dashboard test using community login
 */

test.describe('Master Dashboard Working Tests', () => {
  
  test('Master Dashboard renders correctly with master_trainer user', async ({ page }) => {
    test.setTimeout(60000);
    const actions = new CommonActions(page);
    
    // Navigate to community login page
    await page.goto('https://upskill-staging.measurequick.com/community-login/');
    await page.waitForLoadState('networkidle');
    
    // Login as master_trainer
    await page.fill('#user_login', 'master_trainer');
    await page.fill('#user_pass', 'MasterTrainer#2025!');
    await page.click('#wp-submit');
    
    // Wait for login to complete
    await page.waitForLoadState('networkidle');
    
    // Verify we're logged in by checking URL
    const afterLoginUrl = page.url();
    console.log('URL after login:', afterLoginUrl);
    
    if (afterLoginUrl.includes('hvac-dashboard')) {
      console.log('Successfully logged in and redirected to dashboard');
      
      // Now navigate to master dashboard
      await page.goto('https://upskill-staging.measurequick.com/master-dashboard/');
      await page.waitForLoadState('networkidle');
      
      // Take screenshot
      await page.screenshot({ 
        path: `test-results/screenshots/master-dashboard-logged-in-${Date.now()}.png`,
        fullPage: true 
      });
      
      // Check final URL
      const masterDashUrl = page.url();
      console.log('Master Dashboard URL:', masterDashUrl);
      
      // Check page content
      const pageTitle = await page.title();
      console.log('Page title:', pageTitle);
      
      // Look for dashboard elements
      const h1Count = await page.locator('h1').count();
      console.log('H1 elements found:', h1Count);
      
      if (h1Count > 0) {
        const h1Text = await page.locator('h1').first().textContent();
        console.log('H1 text:', h1Text);
        
        // Expect to see Master Dashboard
        if (h1Text?.includes('Master Dashboard')) {
          console.log('✓ Master Dashboard title found');
          
          // Look for system overview
          const systemOverview = await page.locator('text=System Overview').count();
          console.log('System Overview sections found:', systemOverview);
          
          // Look for stat cards
          const statCards = await page.locator('.hvac-stat-card').count();
          console.log('Stat cards found:', statCards);
          
          // Check for specific stats
          const expectedStats = ['Total Events', 'Active Trainers', 'Total Revenue'];
          for (const stat of expectedStats) {
            const statFound = await page.locator(`text=${stat}`).count();
            console.log(`${stat} found:`, statFound > 0 ? '✓' : '✗');
          }
        } else if (h1Text?.includes('Access Denied')) {
          console.log('✗ Access Denied - master_trainer does not have permission');
        }
      }
    } else {
      console.log('Login failed or redirected elsewhere:', afterLoginUrl);
    }
  });
  
  test('Create and test admin user for Master Dashboard', async ({ page }) => {
    test.setTimeout(60000);
    
    // First login as test_trainer to create events
    await page.goto('https://upskill-staging.measurequick.com/community-login/');
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'Test123!');
    await page.click('#wp-submit');
    await page.waitForLoadState('networkidle');
    
    console.log('Logged in as test_trainer');
    
    // Navigate to manage event to create a test event
    await page.goto('https://upskill-staging.measurequick.com/manage-event/');
    await page.waitForLoadState('networkidle');
    
    // Check if form is visible
    const formVisible = await page.locator('#event-form-section').isVisible();
    if (formVisible) {
      console.log('Event form is visible - creating test event');
      
      // Fill out event form
      const timestamp = Date.now();
      await page.fill('#event_title', `Test Event ${timestamp}`);
      
      // Try to fill description
      try {
        const frame = page.frameLocator('iframe[id*="_ifr"]').first();
        await frame.locator('body').fill(`Test event description ${timestamp}`);
      } catch {
        // Fallback to textarea
        await page.fill('#event_content, textarea[name="content"]', `Test event description ${timestamp}`);
      }
      
      // Submit form
      await page.click('button[type="submit"]');
      await page.waitForLoadState('networkidle');
      
      console.log('Test event created');
    }
    
    // Now we have data, let's verify the master dashboard shows it
    // Logout first
    await page.goto('https://upskill-staging.measurequick.com/wp-login.php?action=logout');
    await page.waitForLoadState('networkidle');
    
    // Click logout confirmation if needed
    const logoutLink = page.locator('a').filter({ hasText: 'log out' });
    if (await logoutLink.count() > 0) {
      await logoutLink.click();
      await page.waitForLoadState('networkidle');
    }
    
    console.log('Logged out - now testing master_trainer access');
    
    // Login as master_trainer again
    await page.goto('https://upskill-staging.measurequick.com/community-login/');
    await page.fill('#user_login', 'master_trainer');
    await page.fill('#user_pass', 'MasterTrainer#2025!');
    await page.click('#wp-submit');
    await page.waitForLoadState('networkidle');
    
    // Go directly to master dashboard
    await page.goto('https://upskill-staging.measurequick.com/master-dashboard/');
    await page.waitForLoadState('networkidle');
    
    // Final screenshot and verification
    await page.screenshot({ 
      path: `test-results/screenshots/master-dashboard-final-test-${Date.now()}.png`,
      fullPage: true 
    });
    
    const finalUrl = page.url();
    console.log('Final URL:', finalUrl);
    
    if (finalUrl.includes('master-dashboard')) {
      console.log('✓ Successfully on master dashboard page');
      expect(page.url()).toContain('master-dashboard');
    } else {
      console.log('✗ Not on master dashboard - may need to verify user permissions');
    }
  });
});