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

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

  test('should create event with proper TinyMCE handling', async ({ page }) => {
    // Enable console logging to debug issues
    page.on('console', msg => {
      if (msg.type() === 'error' || msg.text().includes('required')) {
        console.log(`Console ${msg.type()}: ${msg.text()}`);
      }
    });

    // 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 to load
    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 the page to fully load
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(2000); // Give TinyMCE time to initialize
    
    // Fill event title using proper selector
    const titleField = page.locator('#EventTitle, input[name="EventTitle"]').first();
    await titleField.waitFor({ state: 'visible', timeout: 10000 });
    const eventTitle = `HVAC Training Event ${Date.now()}`;
    await titleField.fill(eventTitle);
    console.log('Filled event title:', eventTitle);
    
    // Handle description field - try multiple approaches
    const descriptionText = 'This is a comprehensive HVAC training event covering installation, maintenance, and troubleshooting. Learn from industry experts.';
    
    // Method 1: Try switching to text mode first
    const textModeButton = page.locator('button:has-text("Text"), .wp-switch-editor.switch-text').first();
    if (await textModeButton.isVisible({ timeout: 1000 })) {
      await textModeButton.click();
      console.log('Switched to text mode');
      await page.waitForTimeout(500);
    }
    
    // Method 2: Fill textarea directly
    const textarea = page.locator('textarea#EventDescription, textarea[name="EventDescription"]').first();
    if (await textarea.isVisible({ timeout: 1000 })) {
      await textarea.fill(descriptionText);
      console.log('Filled description in textarea');
    }
    
    // Method 3: Use JavaScript to set content
    await page.evaluate((desc) => {
      // Try textarea first
      const textareaEl = document.querySelector('textarea#EventDescription, textarea[name="EventDescription"]');
      if (textareaEl) {
        textareaEl.value = desc;
        textareaEl.dispatchEvent(new Event('change', { bubbles: true }));
      }
      
      // Try TinyMCE if available
      if (typeof tinymce !== 'undefined' && tinymce.editors.length > 0) {
        const editor = tinymce.get('EventDescription') || tinymce.editors[0];
        if (editor) {
          editor.setContent(desc);
          editor.save();
        }
      }
    }, descriptionText);
    console.log('Set description via JavaScript');
    
    // Fill date and time fields
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const dateStr = `${(tomorrow.getMonth() + 1).toString().padStart(2, '0')}/${tomorrow.getDate().toString().padStart(2, '0')}/${tomorrow.getFullYear()}`;
    
    // Start date
    const startDateField = page.locator('input[name="EventStartDate"]').first();
    await startDateField.fill(dateStr);
    console.log('Filled start date:', dateStr);
    
    // End date
    const endDateField = page.locator('input[name="EventEndDate"]').first();
    await endDateField.fill(dateStr);
    console.log('Filled end date:', dateStr);
    
    // Fill times if visible
    const startTimeField = page.locator('input[name="EventStartTime"]').first();
    if (await startTimeField.isVisible({ timeout: 1000 })) {
      await startTimeField.fill('9:00am');
      const endTimeField = page.locator('input[name="EventEndTime"]').first();
      await endTimeField.fill('5:00pm');
      console.log('Filled times');
    }
    
    // Scroll down to see more fields
    await page.evaluate(() => window.scrollBy(0, 500));
    await page.waitForTimeout(500);
    
    // Fill venue information if present
    const venueName = page.locator('input[name="venue[Venue]"], input[name="VenueName"]').first();
    if (await venueName.isVisible({ timeout: 1000 })) {
      await venueName.fill('HVAC Training Center');
      console.log('Filled venue name');
    }
    
    // Fill organizer information if present
    const organizerName = page.locator('input[name="organizer[Organizer]"], input[name="OrganizerName"]').first();
    if (await organizerName.isVisible({ timeout: 1000 })) {
      await organizerName.fill('HVAC Expert Trainer');
      console.log('Filled organizer name');
    }
    
    // Scroll to submit button
    const submitButton = page.locator('button:has-text("SUBMIT EVENT"), input[type="submit"][value="SUBMIT EVENT"]').last();
    await submitButton.scrollIntoViewIfNeeded();
    await page.waitForTimeout(500);
    
    // Capture current URL before submission
    const beforeSubmitUrl = page.url();
    
    // Click submit button
    await submitButton.click();
    console.log('Clicked SUBMIT EVENT button');
    
    // Wait for navigation or response
    await page.waitForTimeout(5000);
    
    // Check results
    const afterSubmitUrl = page.url();
    const hasNavigated = beforeSubmitUrl !== afterSubmitUrl;
    const hasSuccess = await page.locator('.tribe-success-msg, .success, .notice-success, .updated').count() > 0;
    const hasErrors = await page.locator('.tribe-error, .error, .notice-error').count() > 0;
    
    console.log('Before URL:', beforeSubmitUrl);
    console.log('After URL:', afterSubmitUrl);
    console.log('Navigated:', hasNavigated);
    console.log('Has success:', hasSuccess);
    console.log('Has errors:', hasErrors);
    
    // Capture error messages if any
    if (hasErrors) {
      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);
      }
    }
    
    // Check for specific validation errors
    const pageContent = await page.content();
    if (pageContent.includes('required') || pageContent.includes('validation')) {
      console.log('Validation errors detected in page content');
    }
    
    // Assert event was created successfully
    expect(hasNavigated || hasSuccess).toBeTruthy();
  });
});