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

test.describe('Event Creation with Cache Clear', () => {
  test('should create community event after clearing Breeze cache', async ({ page }) => {
    // Login as organizer role
    await page.goto(`https://${STAGING_CONFIG.url}/wp-login.php`);
    await page.fill('#user_login', 'organizer');
    await page.fill('#user_pass', 'Organizer123!');
    await page.click('#wp-submit');

    // Wait for dashboard
    await page.waitForURL('**/wp-admin/**');

    // Navigate to Breeze settings to clear cache
    console.log('Navigating to Breeze cache settings...');
    await page.goto(`https://${STAGING_CONFIG.url}/wp-admin/options-general.php?page=breeze`);
    
    // Look for Purge Cache button
    const purgeCacheButton = page.locator('button:has-text("Purge Cache"), a:has-text("Purge Cache")').first();
    if (await purgeCacheButton.isVisible()) {
      await purgeCacheButton.click();
      console.log('Cleared Breeze cache');
      await page.waitForTimeout(2000); // Wait for cache to clear
    } else {
      console.log('Purge cache button not found, trying alternate method');
      
      // Try to clear cache via direct URL
      await page.goto(`https://${STAGING_CONFIG.url}/wp-admin/admin-ajax.php?action=breeze_purge_varnish`);
      await page.waitForTimeout(1000);
      
      // Also try to clear object cache
      await page.goto(`https://${STAGING_CONFIG.url}/wp-admin/admin-ajax.php?action=breeze_purge_cache`);
      await page.waitForTimeout(1000);
    }

    // Navigate to community events
    await page.goto(`https://${STAGING_CONFIG.url}/my-events`);
    
    // Click on Submit Event button
    await page.click('a:has-text("Submit Event")');
    await page.waitForURL('**/community/add**');

    // Fill in the event details
    const title = `HVAC Test Event ${Date.now()}`;
    await page.fill('#post_title', title);

    // Handle description field
    console.log('Filling description field...');
    
    // First, try to fill the textarea directly
    const textarea = page.locator('#tcepostcontent, textarea[name="tcepostcontent"]').first();
    if (await textarea.isVisible()) {
      await textarea.fill('Test description for event creation after cache clear');
      console.log('Filled textarea directly');
    }

    // Also try text mode
    const textTab = page.locator('.wp-switch-editor.switch-text, a:has-text("Text")').first();
    if (await textTab.isVisible()) {
      await textTab.click();
      await page.waitForTimeout(500);
      
      const textArea = page.locator('#tcepostcontent').first();
      await textArea.fill('Test description for event creation after cache clear');
      console.log('Filled text mode textarea');
    }

    // Set up JavaScript evaluation to sync content
    await page.evaluate((desc) => {
      const textarea = document.querySelector('#tcepostcontent');
      if (textarea) {
        textarea.value = desc;
        textarea.dispatchEvent(new Event('change', { bubbles: true }));
        textarea.dispatchEvent(new Event('input', { bubbles: true }));
      }
      
      // Also try to set TinyMCE content if available
      if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
        tinymce.activeEditor.setContent(desc);
        tinymce.activeEditor.save();
      }
    }, 'Test description for event creation after cache clear');

    // Set date/time fields
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    const dateStr = tomorrow.toISOString().split('T')[0];
    await page.fill('#EventStartDate', dateStr);
    await page.fill('#EventEndDate', dateStr);
    await page.fill('#EventStartTime', '10:00 AM');
    await page.fill('#EventEndTime', '12:00 PM');

    // Fill venue information
    const venueName = page.locator('input[name="venue[Venue][]"]').first();
    if (await venueName.isVisible()) {
      await venueName.fill('HVAC Training Center');
    }

    const venueAddress = page.locator('input[name="venue[Address][]"]').first();
    if (await venueAddress.isVisible()) {
      await venueAddress.fill('123 Main Street');
    }

    const venueCity = page.locator('input[name="venue[City][]"]').first();
    if (await venueCity.isVisible()) {
      await venueCity.fill('Atlanta');
    }

    const venueState = page.locator('select[name="venue[State][]"], input[name="venue[State][]"]').first();
    if (await venueState.isVisible()) {
      if (venueState.tagName() === 'SELECT') {
        await venueState.selectOption('GA');
      } else {
        await venueState.fill('GA');
      }
    }

    const venueZip = page.locator('input[name="venue[Zip][]"]').first();
    if (await venueZip.isVisible()) {
      await venueZip.fill('30301');
    }

    // Fill organizer information
    const organizerName = page.locator('input[name="organizer[Organizer][]"]').first();
    if (await organizerName.isVisible()) {
      await organizerName.fill('Test Organizer');
    }

    const organizerEmail = page.locator('input[name="organizer[Email][]"]').first();
    if (await organizerEmail.isVisible()) {
      await organizerEmail.fill('organizer@test.com');
    }

    // Monitor requests and console errors
    const consoleErrors: string[] = [];
    page.on('console', msg => {
      if (msg.type() === 'error') {
        consoleErrors.push(msg.text());
      }
    });

    // Submit the form
    const submitButton = await page.locator('input[type="submit"][name="community-event"]').first();
    const currentUrl = page.url();
    
    await submitButton.click();
    console.log('Clicked submit button');

    // Wait for navigation or error message
    await page.waitForTimeout(5000);

    // Check for success
    const newUrl = page.url();
    const urlChanged = newUrl !== currentUrl;
    const hasErrors = consoleErrors.length > 0;
    const hasSuccessMessage = await page.locator('.tribe-success-msg, .success, .updated').isVisible();

    console.log(`URL changed: ${urlChanged}`);
    console.log(`Has errors: ${hasErrors}`);
    console.log(`Console errors:`, consoleErrors);
    console.log(`Has success: ${hasSuccessMessage}`);

    // Check for validation errors
    const validationErrors = await page.locator('.error, .tribe-error, .tribe-events-error').allTextContents();
    console.log('Validation errors:', validationErrors);

    // Assert event was created
    expect(urlChanged || hasSuccessMessage).toBeTruthy();
  });
});