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('Test Events Verification', () => {
  const stagingUrl = process.env.UPSKILL_STAGING_URL || 'https://upskill-staging.measurequick.com';
  
  test('verify test events exist and ownership', async ({ page }) => {
    const username = process.env.TEST_USERNAME || 'test_trainer';
    const password = process.env.TEST_PASSWORD || 'Test123!';

    console.log('Checking test events and ownership');
    
    // Step 1: Login as test_trainer
    await page.goto(stagingUrl + '/wp-login.php');
    await page.fill('#user_login', username);
    await page.fill('#user_pass', password);
    await page.click('#wp-submit');
    
    await page.waitForURL('**/wp-admin/**');
    console.log('Logged in as test_trainer');

    // Step 2: Check My Events page
    await page.goto(stagingUrl + '/my-events/');
    await page.waitForLoadState('networkidle');
    
    // Check if there are any events for this user
    const myEventsCount = await page.locator('.tribe-events-event-meta, .event-item, .tribe-event, .tribe-events-list-widget').count();
    console.log('Events on My Events page:', myEventsCount);
    
    // Check for "no events" message
    const noEventsMessage = await page.locator('.tribe-events-notices, .no-events-message, :text("no events")').isVisible().catch(() => false);
    console.log('No events message visible:', noEventsMessage);
    
    await page.screenshot({ path: 'test_trainer_my_events.png', fullPage: true });
    
    // Step 3: Go to admin to check all events
    await page.goto(stagingUrl + '/wp-admin/edit.php?post_type=tribe_events');
    await page.waitForLoadState('networkidle');
    
    // Count total events in admin
    const adminEventCount = await page.locator('tbody#the-list tr').count();
    console.log('Total events in admin:', adminEventCount);
    
    // Get event details
    const eventRows = await page.locator('tbody#the-list tr').all();
    for (let i = 0; i < Math.min(5, eventRows.length); i++) {
      const title = await eventRows[i].locator('.row-title').textContent();
      const author = await eventRows[i].locator('.author').textContent().catch(() => 'N/A');
      const status = await eventRows[i].locator('.post-state').textContent().catch(() => 'published');
      console.log(`Event ${i + 1}: "${title}" by ${author} (${status})`);
    }
    
    await page.screenshot({ path: 'all_events_admin.png', fullPage: true });
    
    // Step 4: Create a test event to verify it shows up
    console.log('\nCreating a new test event...');
    await page.goto(stagingUrl + '/manage-event/');
    await page.waitForSelector('input[name="post_title"]', { state: 'visible' });
    
    const testTitle = `Dashboard Test Event ${Date.now()}`;
    await page.fill('input[name="post_title"]', testTitle);
    
    // Fill minimal required fields
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const dateStr = tomorrow.toISOString().split('T')[0];
    
    await page.fill('input[name="EventStartDate"]', dateStr);
    await page.fill('input[name="EventEndDate"]', dateStr);
    await page.fill('input[name="EventStartTime"]', '10:00');
    await page.fill('input[name="EventEndTime"]', '12:00');
    
    // Fill description
    const descField = await page.locator('textarea[name="tcepostcontent"]').isVisible().catch(() => false);
    if (descField) {
      await page.fill('textarea[name="tcepostcontent"]', 'Test event for dashboard verification');
    } else {
      const iframe = page.frameLocator('iframe#tcepostcontent_ifr');
      await iframe.locator('body').fill('Test event for dashboard verification');
    }
    
    // Submit
    await page.click('input[type="submit"][value="Submit Event"]');
    await page.waitForTimeout(5000);
    
    console.log('Test event created');
    
    // Step 5: Check dashboard again
    await page.goto(stagingUrl + '/hvac-dashboard/');
    await page.waitForLoadState('networkidle');
    
    // Wait for stats to load
    await page.waitForTimeout(3000);
    
    // Check stats again
    const totalEventsText = await page.locator('.hvac-stat-block:has-text("Total Events") .hvac-stat-number, :text("Total Events") + * .number, td:has-text("Total Events") + td').textContent().catch(() => '0');
    console.log('Dashboard Total Events after creation:', totalEventsText);
    
    await page.screenshot({ path: 'dashboard_after_event_creation.png', fullPage: true });
    
    // Step 6: Check My Events again
    await page.goto(stagingUrl + '/my-events/');
    await page.waitForLoadState('networkidle');
    
    const newEventsCount = await page.locator('.tribe-events-event-meta, .event-item, .tribe-event').count();
    console.log('Events on My Events page after creation:', newEventsCount);
    
    // Check if our test event appears
    const testEventVisible = await page.locator(`text="${testTitle}"`).isVisible().catch(() => false);
    console.log('Test event visible in My Events:', testEventVisible);
    
    await page.screenshot({ path: 'my_events_after_creation.png', fullPage: true });
    
    // Summary
    console.log('\n=== Summary ===');
    console.log('Initial events for test_trainer:', myEventsCount);
    console.log('Total events in system:', adminEventCount);
    console.log('Test event created successfully');
    console.log('Dashboard shows events:', totalEventsText);
    console.log('Events after creation:', newEventsCount);
    console.log('Test event visible:', testEventVisible);
  });
});