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

// STAGING_URL is now imported from config

test.describe('Working Event Creation', () => {
  test('should successfully create an event with all required fields', async ({ page }) => {
    // Login
    await page.goto(PATHS.login);
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'Test123!');
    await page.click('#wp-submit');
    await page.waitForURL('**/hvac-dashboard/');
    
    // Navigate to create event
    const createEventBtn = page.locator('a:has-text("CREATE EVENT"), a:has-text("Create Event")').first();
    await createEventBtn.click();
    await page.waitForLoadState('networkidle');
    
    // Fill all required fields
    const eventTitle = `HVAC Training Event ${Date.now()}`;
    await page.fill('input[name="post_title"]', eventTitle);
    console.log('Filled title:', eventTitle);
    
    // Fill description - REQUIRED
    // First try to switch to text editor mode
    const textTab = page.locator('#content-text, #content-tmce, .switch-text');
    if (await textTab.isVisible()) {
      await textTab.click();
      await page.waitForTimeout(500);
    }
    
    const description = `This is a comprehensive HVAC training event covering installation, maintenance, and troubleshooting techniques. Created on ${new Date().toLocaleString()}`;
    
    // Try multiple selectors for description
    const descriptionFilled = await page.evaluate((desc) => {
      // Try direct textarea
      const textarea = document.querySelector('textarea[name="post_content"], textarea#content');
      if (textarea) {
        (textarea as HTMLTextAreaElement).value = desc;
        return true;
      }
      
      // Try via jQuery if available
      if (typeof jQuery !== 'undefined') {
        const $textarea = jQuery('#content, textarea[name="post_content"]');
        if ($textarea.length) {
          $textarea.val(desc);
          return true;
        }
      }
      
      return false;
    }, description);
    
    if (!descriptionFilled) {
      // Try the iframe approach
      const iframe = page.frameLocator('iframe[id*="content"], iframe[title*="editor"]').first();
      await iframe.locator('body').fill(description);
    }
    
    console.log('Filled description');
    
    // Fill date and time fields
    const today = new Date();
    const dateStr = `${(today.getMonth() + 1).toString().padStart(2, '0')}/${today.getDate().toString().padStart(2, '0')}/${today.getFullYear()}`;
    
    await page.fill('input#EventStartDate', dateStr);
    await page.fill('input#EventEndDate', dateStr);
    await page.fill('input#EventStartTime', '10:00');
    await page.fill('input#EventEndTime', '12:00');
    console.log('Filled dates and times');
    
    // Check if organizer/venue dropdowns exist and have options
    const organizerSelect = page.locator('select[name="organizer"]');
    if (await organizerSelect.isVisible()) {
      const options = await organizerSelect.locator('option').count();
      if (options > 1) {
        await organizerSelect.selectOption({ index: 1 });
        console.log('Selected organizer');
      }
    }
    
    const venueSelect = page.locator('select[name="venue"]');
    if (await venueSelect.isVisible()) {
      const options = await venueSelect.locator('option').count();
      if (options > 1) {
        await venueSelect.selectOption({ index: 1 });
        console.log('Selected venue');
      }
    }
    
    // Scroll to submit button
    await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
    await page.waitForTimeout(1000);
    
    // Submit the form
    const submitButton = page.locator('input[type="submit"][value="Submit Event"]');
    
    // Listen for navigation
    const navigationPromise = page.waitForNavigation({ 
      timeout: 15000,
      waitUntil: 'networkidle' 
    }).catch(() => null);
    
    await submitButton.click();
    console.log('Clicked submit button');
    
    // Wait for response
    const navigated = await navigationPromise;
    await page.waitForTimeout(3000);
    
    // Take screenshot
    await page.screenshot({ path: 'test-results/working-event-creation-result.png', fullPage: true });
    
    // Check for success
    const currentUrl = page.url();
    console.log('Current URL:', currentUrl);
    
    // Look for success indicators
    const successMessages = [
      '.updated',
      '.notice-success',
      '.tribe-success',
      '.success-message',
      '.message.updated'
    ];
    
    let successFound = false;
    for (const selector of successMessages) {
      if (await page.locator(selector).isVisible()) {
        const text = await page.locator(selector).textContent();
        console.log('Success message found:', text);
        successFound = true;
        break;
      }
    }
    
    // Check if we were redirected to a success page or the event page
    const urlChanged = !currentUrl.includes('/manage-event/');
    const hasEventInUrl = currentUrl.includes('/event/') || currentUrl.includes('/tribe_events/');
    
    console.log('Success found:', successFound);
    console.log('URL changed:', urlChanged);
    console.log('Has event in URL:', hasEventInUrl);
    
    // Success criteria: success message OR URL change OR event URL
    expect(successFound || urlChanged || hasEventInUrl).toBeTruthy();
  });
});