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

// Base configuration
const BASE_URL = 'https://upskill-staging.measurequick.com';
const USER_LOGIN = 'test_trainer';
const USER_PASSWORD = 'Test123!';

// Test event IDs created by our scripts
const TEST_EVENTS = [
  { id: '5641', name: 'HVAC System Design Fundamentals' },
  { id: '5668', name: 'Advanced Refrigeration Technology' },
  { id: '5688', name: 'Building Automation Systems Workshop' }
];

/**
 * Test to verify certificate test data and attendee filtering
 */
test('Verify certificate test data and attendee filtering', async ({ page }) => {
  console.log('Step 1: Logging in...');
  await page.goto(`${BASE_URL}/community-login/`);
  await page.fill('#user_login', USER_LOGIN);
  await page.fill('#user_pass', USER_PASSWORD);
  await page.click('#wp-submit');
  await page.waitForLoadState('networkidle');
  
  // Verify logged in successfully
  const currentUrl = page.url();
  console.log(`Current URL after login: ${currentUrl}`);
  
  // Navigate to certificate reports page
  console.log('Step 2: Navigating to certificate reports page...');
  await page.goto(`${BASE_URL}/certificate-reports/`);
  await page.waitForSelector('.hvac-certificate-reports', { timeout: 10000 });
  
  // Test 1: Verify total certificate count
  const totalCountText = await page.textContent('.hvac-total-count');
  console.log(`Total count text: ${totalCountText}`);
  
  // Extract count from text like "Showing 1-20 of 54 certificates"
  const countMatch = totalCountText?.match(/of (\d+) certificates/);
  const totalCount = countMatch ? parseInt(countMatch[1]) : 0;
  
  console.log(`Total certificates found: ${totalCount}`);
  expect(totalCount).toBeGreaterThanOrEqual(47);
  
  // Test 2: Event filtering
  for (const testEvent of TEST_EVENTS) {
    console.log(`Testing event filter: ${testEvent.name} (ID: ${testEvent.id})`);
    
    // Clear any existing filters first
    await page.click('a.hvac-clear-filters');
    await page.waitForTimeout(500);
    
    // Select the event
    await page.selectOption('#filter_event', { value: testEvent.id });
    await page.click('button[type="submit"]');
    await page.waitForSelector('.hvac-certificate-table');
    
    // Check count text
    const eventFilteredText = await page.textContent('.hvac-total-count');
    const eventCountMatch = eventFilteredText?.match(/of (\d+) certificates/);
    const eventCount = eventCountMatch ? parseInt(eventCountMatch[1]) : 0;
    
    console.log(`Found ${eventCount} certificates for event ${testEvent.name}`);
    expect(eventCount).toBeGreaterThan(0);
    
    // Check event names in table
    const eventCells = await page.$$eval('td.certificate-event', cells => 
      cells.map(cell => cell.textContent?.trim())
    );
    
    // Verify at least one row has the correct event name
    if (eventCells.length > 0) {
      expect(eventCells[0]).toContain(testEvent.name);
    }
  }
  
  // Test 3: Attendee filtering by name
  console.log('Testing attendee name filter: "Ben Tester"');
  
  // Clear any existing filters first
  await page.click('a.hvac-clear-filters');
  await page.waitForTimeout(500);
  
  // Search for Ben Tester
  await page.fill('#search_attendee', 'Ben Tester');
  await page.click('button[type="submit"]');
  await page.waitForSelector('.hvac-certificate-table');
  
  // Check count text
  const nameFilteredText = await page.textContent('.hvac-total-count');
  const nameCountMatch = nameFilteredText?.match(/of (\d+) certificates/);
  const nameCount = nameCountMatch ? parseInt(nameCountMatch[1]) : 0;
  
  console.log(`Found ${nameCount} certificates for attendee name "Ben Tester"`);
  
  // Check attendee names in table
  const attendeeCells = await page.$$eval('td.certificate-attendee', cells => 
    cells.map(cell => cell.textContent?.trim())
  );
  
  // Take screenshot for verification
  await page.screenshot({ path: 'ben-tester-search.png', fullPage: true });
  
  // Test 4: Attendee filtering by email
  console.log('Testing attendee email filter: "ben@tealmaker.com"');
  
  // Clear any existing filters first
  await page.click('a.hvac-clear-filters');
  await page.waitForTimeout(500);
  
  // Search for email
  await page.fill('#search_attendee', 'ben@tealmaker.com');
  await page.click('button[type="submit"]');
  await page.waitForSelector('.hvac-certificate-table');
  
  // Check count text
  const emailFilteredText = await page.textContent('.hvac-total-count');
  const emailCountMatch = emailFilteredText?.match(/of (\d+) certificates/);
  const emailCount = emailCountMatch ? parseInt(emailCountMatch[1]) : 0;
  
  console.log(`Found ${emailCount} certificates for attendee email "ben@tealmaker.com"`);
  
  // Take screenshot for verification
  await page.screenshot({ path: 'ben-email-search.png', fullPage: true });
  
  // Test 5: Partial name filtering
  console.log('Testing partial name filter: "Smith"');
  
  // Clear any existing filters first
  await page.click('a.hvac-clear-filters');
  await page.waitForTimeout(500);
  
  // Search for partial name
  await page.fill('#search_attendee', 'Smith');
  await page.click('button[type="submit"]');
  await page.waitForSelector('.hvac-certificate-table');
  
  // Check count text
  const partialNameText = await page.textContent('.hvac-total-count');
  const partialNameMatch = partialNameText?.match(/of (\d+) certificates/);
  const partialNameCount = partialNameMatch ? parseInt(partialNameMatch[1]) : 0;
  
  console.log(`Found ${partialNameCount} certificates for partial name "Smith"`);
  
  // Take screenshot for verification
  await page.screenshot({ path: 'smith-search.png', fullPage: true });
  
  // Test 6: Partial email filtering
  console.log('Testing partial email filter: "@gmail"');
  
  // Clear any existing filters first
  await page.click('a.hvac-clear-filters');
  await page.waitForTimeout(500);
  
  // Search for partial email
  await page.fill('#search_attendee', '@gmail');
  await page.click('button[type="submit"]');
  await page.waitForSelector('.hvac-certificate-table');
  
  // Check count text
  const partialEmailText = await page.textContent('.hvac-total-count');
  const partialEmailMatch = partialEmailText?.match(/of (\d+) certificates/);
  const partialEmailCount = partialEmailMatch ? parseInt(partialEmailMatch[1]) : 0;
  
  console.log(`Found ${partialEmailCount} certificates for partial email "@gmail"`);
  
  // Take screenshot for verification
  await page.screenshot({ path: 'gmail-search.png', fullPage: true });
  
  // Test 7: Revocation status filtering
  console.log('Testing revocation status filter');
  
  // Clear any existing filters first
  await page.click('a.hvac-clear-filters');
  await page.waitForTimeout(500);
  
  // Filter by revoked certificates
  await page.selectOption('#filter_revoked', { value: '1' });
  await page.click('button[type="submit"]');
  await page.waitForSelector('.hvac-certificate-table');
  
  // Check count text
  const revokedText = await page.textContent('.hvac-total-count');
  const revokedMatch = revokedText?.match(/of (\d+) certificates/);
  const revokedCount = revokedMatch ? parseInt(revokedMatch[1]) : 0;
  
  console.log(`Found ${revokedCount} revoked certificates`);
  
  // Take screenshot for verification
  await page.screenshot({ path: 'revoked-search.png', fullPage: true });
  
  // Test 8: Combined filtering
  console.log('Testing combined filtering (event + attendee)');
  
  // Clear any existing filters first
  await page.click('a.hvac-clear-filters');
  await page.waitForTimeout(500);
  
  // Apply multiple filters
  await page.selectOption('#filter_event', { value: TEST_EVENTS[0].id });
  await page.fill('#search_attendee', 'Ben');
  await page.click('button[type="submit"]');
  await page.waitForSelector('.hvac-certificate-table');
  
  // Check count text
  const combinedText = await page.textContent('.hvac-total-count');
  console.log(`Combined filter results: ${combinedText}`);
  
  // Take screenshot for verification
  await page.screenshot({ path: 'combined-search.png', fullPage: true });
  
  // Final test: Check pagination
  console.log('Testing pagination');
  
  // Clear any existing filters first
  await page.click('a.hvac-clear-filters');
  await page.waitForTimeout(500);
  
  // Check if pagination is present
  const hasPagination = await page.$('.hvac-pagination');
  console.log(`Has pagination: ${hasPagination !== null}`);
  
  if (hasPagination) {
    const currentPage = await page.$eval('.hvac-pagination .current', el => el.textContent?.trim());
    console.log(`Current page: ${currentPage}`);
    
    const hasNextPage = await page.$('.hvac-pagination a.next');
    if (hasNextPage) {
      await page.click('.hvac-pagination a.next');
      await page.waitForSelector('.hvac-certificate-table');
      
      const newPage = await page.$eval('.hvac-pagination .current', el => el.textContent?.trim());
      console.log(`New page: ${newPage}`);
      
      expect(newPage).not.toEqual(currentPage);
    }
  }
  
  console.log('Certificate test data verification completed');
});