import { STAGING_URL, PATHS, TIMEOUTS } from './config/staging-config';
import { test, expect } from '@playwright/test';
import * as dotenv from 'dotenv';
import { resolve } from 'path';

dotenv.config({ path: resolve(__dirname, '../../../../.env') });

test.use({
  screenshot: 'on',
  video: 'on',
  trace: 'on',
  actionTimeout: 15000,
  timeout: 60000
});

test.describe('Dashboard Stats Verification', () => {
  const stagingUrl = process.env.UPSKILL_STAGING_URL || 'https://upskill-staging.measurequick.com';
  
  test('verify dashboard shows test event statistics', async ({ page }) => {
    const username = process.env.TEST_USERNAME || 'test_trainer';
    const password = process.env.TEST_PASSWORD || 'Test123!';

    console.log('Starting dashboard stats check');
    
    // Step 1: Login via wp-admin
    await page.goto(stagingUrl + '/wp-login.php');
    await page.fill('#user_login', username);
    await page.fill('#user_pass', password);
    await page.click('#wp-submit');
    
    // Wait for login
    await page.waitForURL('**/wp-admin/**');
    console.log('Logged in successfully');

    // Step 2: Navigate to dashboard
    await page.goto(stagingUrl + '/hvac-dashboard/');
    await page.waitForLoadState('networkidle');
    
    // Wait for dashboard to load
    await page.waitForSelector('.hvac-dashboard-container', { state: 'visible' });
    console.log('Dashboard loaded');
    
    // Step 3: Check for statistics
    const statsSelectors = {
      totalEvents: '.hvac-stat-block:has-text("Total Events") .hvac-stat-number',
      upcomingEvents: '.hvac-stat-block:has-text("Upcoming Events") .hvac-stat-number',
      totalRevenue: '.hvac-stat-block:has-text("Total Revenue") .hvac-stat-number',
      totalTrainees: '.hvac-stat-block:has-text("Total Trainees") .hvac-stat-number'
    };
    
    const stats = {};
    
    for (const [key, selector] of Object.entries(statsSelectors)) {
      try {
        await page.waitForSelector(selector, { state: 'visible', timeout: 5000 });
        const value = await page.textContent(selector);
        stats[key] = value?.trim();
        console.log(`${key}: ${stats[key]}`);
      } catch (e) {
        console.log(`Could not find ${key} stats`);
        stats[key] = 'Not found';
      }
    }
    
    // Step 4: Check for recent events list
    const recentEventsExists = await page.locator('.hvac-recent-events').isVisible().catch(() => false);
    console.log('Recent events section exists:', recentEventsExists);
    
    if (recentEventsExists) {
      const eventItems = await page.locator('.hvac-event-item').count();
      console.log('Number of recent events:', eventItems);
      
      // Get event titles
      const eventTitles = await page.locator('.hvac-event-title').allTextContents();
      console.log('Event titles:', eventTitles);
    }
    
    // Step 5: Check for chart/graph
    const chartExists = await page.locator('#attendeesChart, #revenueChart, .chart-container').isVisible().catch(() => false);
    console.log('Chart exists:', chartExists);
    
    // Take screenshot of dashboard
    await page.screenshot({ path: 'dashboard-stats-check.png', fullPage: true });
    
    // Step 6: Navigate to My Events to count actual events
    await page.goto(stagingUrl + '/my-events/');
    await page.waitForLoadState('networkidle');
    
    const myEventsTitle = await page.locator('h1, h2').first().textContent();
    console.log('My Events page title:', myEventsTitle);
    
    // Count events in the list
    const eventCount = await page.locator('.tribe-events-event-meta, .event-listing, .tribe-event').count();
    console.log('Total events in My Events:', eventCount);
    
    // Take screenshot of My Events
    await page.screenshot({ path: 'my-events-list.png', fullPage: true });
    
    // Step 7: Verify data consistency
    console.log('\n=== Dashboard Statistics Summary ===');
    console.log('Dashboard Stats:', stats);
    console.log('Actual event count from My Events:', eventCount);
    
    // Check if Total Events matches actual count
    if (stats.totalEvents !== 'Not found') {
      const dashboardTotal = parseInt(stats.totalEvents.replace(/[^0-9]/g, ''));
      console.log('Dashboard shows total:', dashboardTotal);
      console.log('My Events shows:', eventCount);
      
      if (dashboardTotal !== eventCount) {
        console.warn('⚠️ Mismatch: Dashboard shows', dashboardTotal, 'but My Events has', eventCount);
      } else {
        console.log('✅ Dashboard stats match actual event count');
      }
    }
    
    // Check if stats are being updated from test events
    const hasTestEvents = stats.totalEvents !== '0' && stats.totalEvents !== 'Not found';
    if (hasTestEvents) {
      console.log('✅ Dashboard is showing test event statistics');
    } else {
      console.log('❌ Dashboard is not showing any event statistics');
    }
  });
});