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

test.describe('Final Event Creation Test', () => {
  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 create event handling TinyMCE properly', 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
    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);
    
    // Handle description field using TinyMCE iframe
    const descriptionText = 'This is a comprehensive HVAC training event covering installation, maintenance, and troubleshooting. Learn from industry experts in a hands-on environment. This training will help you advance your HVAC career.';
    
    // Check if we need to handle an iframe for TinyMCE
    const iframe = page.frameLocator('iframe#tcepostcontent_ifr');
    const iframeBody = iframe.locator('body');
    
    try {
      // Try to type into the iframe
      await iframeBody.click();
      await iframeBody.type(descriptionText);
      console.log('Typed description into TinyMCE iframe');
    } catch (e) {
      console.log('TinyMCE iframe approach failed, trying direct JavaScript');
      
      // Use JavaScript to set content directly
      await page.evaluate((text) => {
        // Try TinyMCE first
        if (typeof tinymce !== 'undefined') {
          const editors = tinymce.editors;
          for (let i = 0; i < editors.length; i++) {
            const editor = editors[i];
            if (editor.id === 'tcepostcontent' || editor.id.includes('content')) {
              editor.setContent(text);
              editor.save();
              return;
            }
          }
          
          // If no specific editor found, use the first one
          if (editors.length > 0) {
            editors[0].setContent(text);
            editors[0].save();
          }
        }
        
        // Also set the hidden textarea directly
        const textarea = document.querySelector('textarea[name="tcepostcontent"]');
        if (textarea) {
          textarea.value = text;
          textarea.style.display = 'block'; // Make it visible
          textarea.style.visibility = 'visible';
          textarea.dispatchEvent(new Event('change', { bubbles: true }));
        }
        
        // Try other textareas
        const allTextareas = document.querySelectorAll('textarea');
        allTextareas.forEach(ta => {
          if (ta.name.includes('content') || ta.id.includes('content')) {
            ta.value = text;
            ta.dispatchEvent(new Event('change', { bubbles: true }));
          }
        });
      }, descriptionText);
      console.log('Set description via JavaScript');
    }
    
    // Fill date fields
    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][]"]').first();
    if (await venueName.isVisible({ timeout: 1000 })) {
      await venueName.fill('HVAC Training Center');
      await page.fill('input[name="venue[Address][]"]', '123 Main Street');
      await page.fill('input[name="venue[City][]"]', 'Atlanta');
      
      // Try to select state
      const stateSelect = page.locator('select[name="venue[State][]"]');
      if (await stateSelect.isVisible()) {
        await stateSelect.selectOption('GA');
      } else {
        // Try text input for state
        const stateInput = page.locator('input[name="venue[State][]"], input[name="venue[Province][]"]').first();
        if (await stateInput.isVisible()) {
          await stateInput.fill('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][]"]').first();
    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');
    }
    
    // Take a screenshot before submission
    await page.screenshot({ path: 'test-results/pre-submit-final.png', fullPage: true });
    
    // Ensure TinyMCE content is saved before submission
    await page.evaluate(() => {
      if (typeof tinymce !== 'undefined' && tinymce.editors.length > 0) {
        tinymce.triggerSave();
      }
    });
    
    // 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(10000);
    
    // Take a screenshot after submission
    await page.screenshot({ path: 'test-results/post-submit-final.png', fullPage: true });
    
    // 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);
    
    // Get any 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);
      }
    }
    
    if (hasSuccessMessage) {
      const successElements = await page.locator('.tribe-success-msg, .success, .notice-success, .updated').all();
      for (const element of successElements) {
        const text = await element.textContent();
        console.log('Success message:', text);
      }
    }
    
    // Check the page content for specific error messages
    const pageContent = await page.content();
    if (pageContent.includes('Event Description is required')) {
      console.log('Found description validation error in page content');
      
      // Log what's in the textarea
      const textareaValue = await page.evaluate(() => {
        const ta = document.querySelector('textarea[name="tcepostcontent"]');
        return ta ? ta.value : 'not found';
      });
      console.log('Textarea value:', textareaValue);
      
      // Log what's in TinyMCE
      const tinymceContent = await page.evaluate(() => {
        if (typeof tinymce !== 'undefined' && tinymce.editors.length > 0) {
          return tinymce.editors[0].getContent();
        }
        return 'TinyMCE not found';
      });
      console.log('TinyMCE content:', tinymceContent);
    }
    
    // Assert success
    expect(hasNavigated || hasSuccessMessage).toBeTruthy();
  });
});