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

test.describe('Complete Event Creation', () => {
  test('should create event with all required fields', 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 navigation
    await page.waitForTimeout(3000);
    console.log('Logged in successfully');
    
    // Navigate to manage-event page
    await page.goto(`https://${STAGING_CONFIG.url}/manage-event/`);
    console.log('Navigated to manage-event page');
    
    // Wait for form to load
    await page.waitForSelector('input[name="EventTitle"]', { timeout: 10000 });
    
    // Fill event title
    const eventTitle = `HVAC Training Event ${Date.now()}`;
    await page.fill('input[name="EventTitle"]', eventTitle);
    console.log('Filled event title:', eventTitle);
    
    // Fill event description - using the visible TinyMCE editor
    const descriptionFrame = page.frameLocator('#EventDescription_ifr');
    if (await descriptionFrame.locator('body').isVisible().catch(() => false)) {
      await descriptionFrame.locator('body').click();
      await descriptionFrame.locator('body').fill('This is a comprehensive HVAC training event covering installation, maintenance, and troubleshooting.');
      console.log('Filled description in TinyMCE');
    } else {
      // Try text mode if iframe not visible
      const textarea = page.locator('textarea#EventDescription');
      if (await textarea.isVisible()) {
        await textarea.fill('This is a comprehensive HVAC training event covering installation, maintenance, and troubleshooting.');
        console.log('Filled description in textarea');
      }
    }
    
    // Fill date and time
    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()}`;
    
    await page.fill('input[name="EventStartDate"]', dateStr);
    await page.fill('input[name="EventEndDate"]', dateStr);
    console.log('Filled dates:', dateStr);
    
    // Fill time (if visible)
    if (await page.locator('input[name="EventStartTime"]').isVisible()) {
      await page.fill('input[name="EventStartTime"]', '9:00am');
      await page.fill('input[name="EventEndTime"]', '5:00pm');
      console.log('Filled times');
    }
    
    // Upload image if button is visible
    const uploadButton = page.locator('button:has-text("CHOOSE IMAGE")');
    if (await uploadButton.isVisible()) {
      await uploadButton.click();
      await page.waitForTimeout(1000);
      // Click "Upload files" tab if media library opens
      const uploadTab = page.locator('a:has-text("Upload files")');
      if (await uploadTab.isVisible()) {
        await uploadTab.click();
      }
      // Close media library for now
      const closeButton = page.locator('.media-modal-close');
      if (await closeButton.isVisible()) {
        await closeButton.click();
      }
    }
    
    // Fill venue details
    const venueName = page.locator('input[name="VenueName"], input[name="Venue[Venue]"]').first();
    if (await venueName.isVisible()) {
      await venueName.fill('HVAC Training Center');
      console.log('Filled venue name');
    }
    
    // Fill organizer details
    const organizerName = page.locator('input[name="OrganizerName"], input[name="Organizer[Organizer]"]').first();
    if (await organizerName.isVisible()) {
      await organizerName.fill('Test Organizer');
      console.log('Filled organizer name');
    }
    
    // Fill event website (if required)
    const eventWebsite = page.locator('input[name="EventURL"]');
    if (await eventWebsite.isVisible()) {
      await eventWebsite.fill('https://example.com/hvac-training');
      console.log('Filled event website');
    }
    
    // Click the final submit button
    const submitButton = page.locator('button:has-text("SUBMIT EVENT")').last();
    await submitButton.scrollIntoViewIfNeeded();
    await submitButton.click();
    console.log('Clicked SUBMIT EVENT button');
    
    // Wait for response
    await page.waitForTimeout(5000);
    
    // Check for success
    const currentUrl = page.url();
    const hasSuccess = await page.locator('.tribe-success-msg, .success, .notice-success').isVisible().catch(() => false);
    const hasErrors = await page.locator('.tribe-error, .error, .notice-error').isVisible().catch(() => false);
    
    console.log('Current URL:', currentUrl);
    console.log('Has success:', hasSuccess);
    console.log('Has errors:', hasErrors);
    
    // Get any error messages
    if (hasErrors) {
      const errorTexts = await page.locator('.tribe-error, .error, .notice-error').allTextContents();
      console.log('Error messages:', errorTexts);
    }
    
    // Check if we're redirected to event page or list
    const isEventCreated = currentUrl.includes('/event/') || currentUrl.includes('/my-events/') || hasSuccess;
    
    // Assert event was created
    expect(isEventCreated).toBeTruthy();
  });
});