import { test, expect } from '@playwright/test';
import { STAGING_CONFIG } from '../../playwright.config';
import { execSync } from 'child_process';

test.describe('Working Event Creation', () => {
  test.beforeEach(async () => {
    // Clear cache before each test
    console.log('Clearing cache...');
    try {
      execSync('./bin/clear-breeze-cache.sh', { cwd: process.cwd() });
    } catch (error) {
      console.log('Cache clearing error:', error.message);
    }
  });

  test('should successfully create an event', async ({ page }) => {
    // Login as test_trainer
    await page.goto(`https://${STAGING_CONFIG.url}/wp-login.php`);
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'Test123!');
    await page.click('#wp-submit');
    
    // Wait for dashboard
    await page.waitForURL('**/hvac-dashboard/**', { timeout: 10000 });
    console.log('Logged in successfully');
    
    // Navigate to event creation page
    await page.goto(`https://${STAGING_CONFIG.url}/manage-event/`);
    console.log('Navigated to manage-event page');
    
    // Wait for page to fully load
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(3000);
    
    // Fill event title - using the correct field name "post_title"
    const titleField = page.locator('input[name="post_title"]');
    await titleField.waitFor({ state: 'visible', timeout: 10000 });
    const eventTitle = `HVAC Training Event ${Date.now()}`;
    await titleField.fill(eventTitle);
    console.log('Filled event title:', eventTitle);
    
    // Fill description - the textarea is named "tcepostcontent"
    const descriptionText = 'This is a comprehensive HVAC training event covering installation, maintenance, and troubleshooting. Learn from industry experts in a hands-on environment.';
    
    // First try to use text mode
    const textModeButton = page.locator('button:has-text("Text")').first();
    if (await textModeButton.isVisible({ timeout: 1000 })) {
      await textModeButton.click();
      console.log('Switched to text mode');
      await page.waitForTimeout(500);
    }
    
    // Fill the textarea
    const descriptionTextarea = page.locator('textarea[name="tcepostcontent"]');
    await descriptionTextarea.fill(descriptionText);
    console.log('Filled description in textarea');
    
    // Also try to sync with TinyMCE if available
    await page.evaluate((text) => {
      const textarea = document.querySelector('textarea[name="tcepostcontent"]');
      if (textarea) {
        textarea.value = text;
        textarea.dispatchEvent(new Event('change', { bubbles: true }));
      }
      
      // Try to sync with TinyMCE
      if (typeof tinymce !== 'undefined' && tinymce.get('tcepostcontent')) {
        const editor = tinymce.get('tcepostcontent');
        editor.setContent(text);
        editor.save();
      }
    }, descriptionText);
    
    // Fill date fields (already have default values but we'll update them)
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const dateStr = `${tomorrow.getMonth() + 1}/${tomorrow.getDate()}/${tomorrow.getFullYear()}`;
    
    await page.fill('input[name="EventStartDate"]', dateStr);
    await page.fill('input[name="EventEndDate"]', dateStr);
    console.log('Filled dates:', dateStr);
    
    // Update time fields
    await page.fill('input[name="EventStartTime"]', '9:00am');
    await page.fill('input[name="EventEndTime"]', '5:00pm');
    console.log('Filled times');
    
    // Fill venue information
    const venueName = page.locator('input[name="venue[Venue][]"]');
    if (await venueName.isVisible({ timeout: 1000 })) {
      await venueName.fill('HVAC Training Center');
      
      // Fill venue address
      await page.fill('input[name="venue[Address][]"]', '123 Main Street');
      await page.fill('input[name="venue[City][]"]', 'Atlanta');
      
      // Select state
      const stateSelect = page.locator('select[name="venue[State][]"]');
      if (await stateSelect.isVisible()) {
        await stateSelect.selectOption('GA');
      }
      
      await page.fill('input[name="venue[Zip][]"]', '30301');
      console.log('Filled venue information');
    }
    
    // Fill organizer information
    const organizerName = page.locator('input[name="organizer[Organizer][]"]');
    if (await organizerName.isVisible({ timeout: 1000 })) {
      await organizerName.fill('HVAC Training Institute');
      await page.fill('input[name="organizer[Email][]"]', 'training@hvacupskill.com');
      await page.fill('input[name="organizer[Phone][]"]', '555-1234');
      console.log('Filled organizer information');
    }
    
    // Fill event URL
    const eventURL = page.locator('input[name="EventURL"]');
    if (await eventURL.isVisible()) {
      await eventURL.fill('https://example.com/hvac-training');
      console.log('Filled event URL');
    }
    
    // Scroll to submit button
    await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
    await page.waitForTimeout(1000);
    
    // Find and click the submit button
    const submitButton = page.locator('input[type="submit"][value="Submit Event"]');
    await submitButton.waitFor({ state: 'visible', timeout: 5000 });
    
    // Capture URL before submission
    const beforeSubmitUrl = page.url();
    
    // Click submit
    await submitButton.click();
    console.log('Clicked submit button');
    
    // Wait for response
    await page.waitForTimeout(7000);
    
    // Check results
    const afterSubmitUrl = page.url();
    const hasNavigated = beforeSubmitUrl !== afterSubmitUrl;
    
    console.log('Before URL:', beforeSubmitUrl);
    console.log('After URL:', afterSubmitUrl);
    console.log('Navigation occurred:', hasNavigated);
    
    // Look for success indicators
    const hasSuccessMessage = await page.locator('.tribe-success-msg, .success, .notice-success, .updated').count() > 0;
    const hasErrorMessage = await page.locator('.tribe-error, .error, .notice-error').count() > 0;
    
    console.log('Has success message:', hasSuccessMessage);
    console.log('Has error message:', hasErrorMessage);
    
    // Check for specific validation errors in console or page
    const pageContent = await page.content();
    if (pageContent.includes('required') && pageContent.includes('Description')) {
      console.log('Description validation error detected');
      
      // Try to fill description again if needed
      const textarea = page.locator('textarea[name="tcepostcontent"]');
      const currentValue = await textarea.inputValue();
      console.log('Current description value:', currentValue);
    }
    
    // Get any error messages
    if (hasErrorMessage) {
      const errorElements = await page.locator('.tribe-error, .error, .notice-error').all();
      for (const element of errorElements) {
        const text = await element.textContent();
        console.log('Error message:', text);
      }
    }
    
    // Assert success
    expect(hasNavigated || hasSuccessMessage).toBeTruthy();
  });
});