import { STAGING_URL, PATHS, TIMEOUTS } from './config/staging-config';
import { test, expect } from '@playwright/test';

// STAGING_URL is now imported from config

test.describe('Verify Dashboard Fix', () => {
  test('Check dashboard stats after cache clear', async ({ page, context }) => {
    console.log('Starting test with fresh context...');
    
    // Clear cookies and cache
    await context.clearCookies();
    
    // Login to staging
    console.log('Logging in to staging...');
    await page.goto(PATHS.login);
    
    // Fill in login details
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'Test123!');
    await page.click('#wp-submit');
    
    // Wait for navigation to dashboard
    await page.waitForURL('**/hvac-dashboard/', { waitUntil: 'networkidle' });
    
    // Force a fresh load with cache disabled
    await page.route('**/*', route => {
      route.continue({
        headers: {
          ...route.request().headers(),
          'cache-control': 'no-cache'
        }
      });
    });
    
    // Navigate to dashboard again with no cache
    console.log('Navigating to dashboard with cache disabled...');
    await page.goto(PATHS.dashboard, { waitUntil: 'networkidle' });
    
    // Take screenshot for debugging
    await page.screenshot({ path: 'test-results/dashboard-after-fix.png', fullPage: true });
    
    // Log the entire response
    console.log('Checking dashboard HTML...');
    const dashboardHTML = await page.content();
    console.log('Dashboard content length:', dashboardHTML.length);
    
    // Check stats from data attributes if available
    const statCards = await page.$$eval('.hvac-stat-card', cards => 
      cards.map(card => {
        const titleEl = card.querySelector('h3');
        const valueEl = card.querySelector('p');
        const title = titleEl?.textContent || '';
        const value = valueEl?.textContent || '';
        
        // Check for any data attributes that might contain the real data
        const dataAttrs: Record<string, string> = {};
        for (const attr of valueEl?.attributes || []) {
          if (attr.name.startsWith('data-')) {
            dataAttrs[attr.name] = attr.value;
          }
        }
        
        return { title, value, dataAttrs };
      })
    );
    
    console.log('Stat cards:', JSON.stringify(statCards, null, 2));
    
    // Look for actual counts
    const totalEvents = statCards.find(card => card.title.includes('Total Events'));
    const upcomingEvents = statCards.find(card => card.title.includes('Upcoming Events'));
    const pastEvents = statCards.find(card => card.title.includes('Past Events'));
    
    console.log('Total Events:', totalEvents);
    console.log('Upcoming Events:', upcomingEvents);
    console.log('Past Events:', pastEvents);
    
    // Check if the fix is actually applied
    console.log('Checking if dashboard data is loading correctly...');
    const serverData = await page.evaluate(() => {
      // Check window object for any dashboard data
      return {
        window: Object.keys(window).filter(key => key.includes('dashboard') || key.includes('hvac')),
        hvac: (window as any).hvacDashboard || null,
        ajaxurl: (window as any).ajaxurl || null
      };
    });
    
    console.log('Server data:', serverData);
    
    // Make a direct API call to check dashboard data
    if (serverData.ajaxurl) {
      console.log('Making direct AJAX call to get dashboard data...');
      const response = await page.evaluate(async (ajaxurl) => {
        try {
          const formData = new FormData();
          formData.append('action', 'hvac_get_dashboard_data');
          
          const response = await fetch(ajaxurl, {
            method: 'POST',
            body: formData,
            credentials: 'same-origin'
          });
          
          return await response.text();
        } catch (error) {
          return 'Error: ' + error;
        }
      }, serverData.ajaxurl);
      
      console.log('AJAX response:', response);
    }
    
    // Verify the fix worked
    const totalEventsValue = totalEvents?.value || '0';
    const upcomingEventsValue = upcomingEvents?.value || '0';
    const pastEventsValue = pastEvents?.value || '0';
    
    console.log('Final values:');
    console.log(`Total Events: ${totalEventsValue}`);
    console.log(`Upcoming Events: ${upcomingEventsValue}`);
    console.log(`Past Events: ${pastEventsValue}`);
    
    // The test should show non-zero values now
    expect(parseInt(totalEventsValue)).toBeGreaterThan(0);
    expect(parseInt(upcomingEventsValue)).toBeGreaterThan(0);
    expect(parseInt(pastEventsValue)).toBeGreaterThan(0);
  });
});