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

test.describe('Event Creation via Manage Event', () => {
  test('should create event via manage-event page', 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.waitForTimeout(2000);
    
    // Look for form fields
    const fields = {
      title: ['#post_title', 'input[name="title"]', 'input[name="EventTitle"]', '#tribe-event-title'],
      description: ['#tcepostcontent', 'textarea[name="tcepostcontent"]', '#content', 'textarea[name="content"]'],
      startDate: ['#EventStartDate', 'input[name="EventStartDate"]', 'input[name="event[start_date]"]'],
      endDate: ['#EventEndDate', 'input[name="EventEndDate"]', 'input[name="event[end_date]"]']
    };
    
    // Try to find and fill title
    for (const selector of fields.title) {
      try {
        const element = page.locator(selector).first();
        if (await element.isVisible({ timeout: 1000 })) {
          await element.fill(`HVAC Training Event ${Date.now()}`);
          console.log(`Filled title using selector: ${selector}`);
          break;
        }
      } catch (e) {
        console.log(`Selector ${selector} not found`);
      }
    }
    
    // Try to find and fill description
    for (const selector of fields.description) {
      try {
        const element = page.locator(selector).first();
        if (await element.isVisible({ timeout: 1000 })) {
          await element.fill('This is a test event created via automated testing');
          console.log(`Filled description using selector: ${selector}`);
          break;
        }
      } catch (e) {
        console.log(`Selector ${selector} not found`);
      }
    }
    
    // Try to find and fill dates
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const dateStr = tomorrow.toISOString().split('T')[0];
    
    for (const selector of fields.startDate) {
      try {
        const element = page.locator(selector).first();
        if (await element.isVisible({ timeout: 1000 })) {
          await element.fill(dateStr);
          console.log(`Filled start date using selector: ${selector}`);
          break;
        }
      } catch (e) {
        console.log(`Selector ${selector} not found`);
      }
    }
    
    for (const selector of fields.endDate) {
      try {
        const element = page.locator(selector).first();
        if (await element.isVisible({ timeout: 1000 })) {
          await element.fill(dateStr);
          console.log(`Filled end date using selector: ${selector}`);
          break;
        }
      } catch (e) {
        console.log(`Selector ${selector} not found`);
      }
    }
    
    // Look for submit button
    const submitSelectors = [
      'input[type="submit"][name="community-event"]',
      'button[type="submit"]',
      'input[type="submit"][value*="Submit"]',
      'input[type="submit"][value*="Publish"]',
      'button:has-text("Submit")',
      'button:has-text("Publish")',
      'input[type="submit"]'
    ];
    
    let submitted = false;
    for (const selector of submitSelectors) {
      try {
        const button = page.locator(selector).first();
        if (await button.isVisible({ timeout: 1000 })) {
          const value = await button.getAttribute('value') || await button.textContent();
          console.log(`Found submit button: ${selector} with text/value: ${value}`);
          
          const beforeUrl = page.url();
          await button.click();
          console.log('Clicked submit button');
          
          // Wait for response
          await page.waitForTimeout(5000);
          
          const afterUrl = page.url();
          if (beforeUrl !== afterUrl) {
            console.log(`Navigation occurred: ${beforeUrl} -> ${afterUrl}`);
            submitted = true;
            break;
          }
        }
      } catch (e) {
        console.log(`Submit button ${selector} not found`);
      }
    }
    
    // Check for success messages
    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('Has success message:', hasSuccess);
    console.log('Has error message:', hasErrors);
    
    // Get any messages
    if (hasErrors) {
      const errorTexts = await page.locator('.tribe-error, .error, .notice-error').allTextContents();
      console.log('Error messages:', errorTexts);
    }
    
    if (hasSuccess) {
      const successTexts = await page.locator('.tribe-success-msg, .success, .notice-success').allTextContents();
      console.log('Success messages:', successTexts);
    }
    
    // Assert event was created
    expect(submitted || hasSuccess).toBeTruthy();
  });
});