import { test, expect } from './fixtures/auth';
import { CommonActions } from './utils/common-actions';

/**
 * Event Creation Tests for The Events Calendar Community Events
 * 
 * These tests work with the actual TEC Community Events form structure
 * after removing the custom HVAC override.
 */
test.describe('Event Creation - TEC Community Events', () => {
  test('Create a new event using TEC form', async ({ authenticatedPage: page }) => {
    test.setTimeout(60000); // 1 minute timeout
    const actions = new CommonActions(page);

    // Navigate to Create Event page
    await actions.navigateAndWait('/manage-event/');
    await actions.screenshot('tec-create-event-page');
    
    // Wait for the form to be fully loaded
    await page.waitForLoadState('networkidle');
    
    // TEC Community Events typically uses these form selectors
    // The form ID varies but commonly includes 'tribe-community-events'
    const formSelectors = {
      form: 'form#tribe-community-events, form.tribe-community-events-form, form[id*="community-events"]',
      title: 'input[name="post_title"], input#post_title',
      content: 'textarea[name="post_content"], textarea#tcepostcontent, #tcepostcontent_ifr', // May use TinyMCE
      startDate: 'input[name="EventStartDate"], input#EventStartDate',
      startTime: 'input[name="EventStartTime"], input#EventStartTime',
      endDate: 'input[name="EventEndDate"], input#EventEndDate',
      endTime: 'input[name="EventEndTime"], input#EventEndTime',
      venue: 'input[name="venue[Venue]"], input#venue-venue',
      address: 'input[name="venue[Address]"], input#venue-address',
      city: 'input[name="venue[City]"], input#venue-city',
      submitButton: 'input[type="submit"][name="community-event"], button[type="submit"], input.button-primary[type="submit"]'
    };
    
    // Wait for form to be present
    const form = page.locator(formSelectors.form);
    await expect(form).toBeVisible({ timeout: 10000 });
    
    // Create unique event data
    const eventData = actions.generateTestData('Event');
    const eventDetails = {
      title: eventData.title,
      description: `${eventData.description}\n\nThis event covers advanced HVAC techniques including system optimization and troubleshooting.`,
      startDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days from now
      venue: 'HVAC Training Center',
      address: '123 Main Street',
      city: 'Austin'
    };
    
    // Fill in event title
    const titleField = page.locator(formSelectors.title).first();
    await expect(titleField).toBeVisible();
    await titleField.fill(eventDetails.title);
    
    // Fill in event description
    // Check if using TinyMCE or regular textarea
    const tinyMCE = page.frameLocator('#tcepostcontent_ifr');
    const tinyMCEBody = tinyMCE.locator('body');
    if (await tinyMCEBody.count() > 0) {
      // TinyMCE editor
      await tinyMCEBody.fill(eventDetails.description);
    } else {
      // Regular textarea
      const contentField = page.locator(formSelectors.content).first();
      await contentField.fill(eventDetails.description);
    }
    
    // Fill in event dates
    const startDateField = page.locator(formSelectors.startDate).first();
    if (await startDateField.count() > 0) {
      await startDateField.fill(eventDetails.startDate.toISOString().split('T')[0]);
      
      // Time fields if separate
      const startTimeField = page.locator(formSelectors.startTime).first();
      if (await startTimeField.count() > 0) {
        await startTimeField.fill('09:00 AM');
      }
      
      // End date/time
      const endDateField = page.locator(formSelectors.endDate).first();
      if (await endDateField.count() > 0) {
        await endDateField.fill(eventDetails.startDate.toISOString().split('T')[0]);
        
        const endTimeField = page.locator(formSelectors.endTime).first();
        if (await endTimeField.count() > 0) {
          await endTimeField.fill('05:00 PM');
        }
      }
    }
    
    // Fill in venue information
    const venueField = page.locator(formSelectors.venue).first();
    if (await venueField.count() > 0) {
      await venueField.fill(eventDetails.venue);
      
      const addressField = page.locator(formSelectors.address).first();
      if (await addressField.count() > 0) {
        await addressField.fill(eventDetails.address);
      }
      
      const cityField = page.locator(formSelectors.city).first();
      if (await cityField.count() > 0) {
        await cityField.fill(eventDetails.city);
      }
    }
    
    await actions.screenshot('tec-form-filled');
    
    // Submit the form
    const submitButton = page.locator(formSelectors.submitButton).first();
    await expect(submitButton).toBeVisible();
    
    // Click submit and wait for navigation or success message
    await Promise.all([
      page.waitForURL(/\/(event-submitted|my-events|hvac-dashboard|manage-event)/, { timeout: 30000 }).catch(() => {}),
      page.waitForSelector('.tribe-success, .updated, .notice-success', { timeout: 30000 }).catch(() => {}),
      submitButton.click()
    ]);
    
    await actions.screenshot('tec-after-submit');
    
    // Check for success indicators
    const successMessage = page.locator('.tribe-success, .updated, .notice-success').first();
    const hasSuccessMessage = await successMessage.count() > 0;
    
    if (hasSuccessMessage) {
      console.log('Success message found:', await successMessage.textContent());
    }
    
    // Navigate to dashboard to verify event appears
    await actions.navigateAndWait('/hvac-dashboard/');
    
    // Look for the event in the events table
    const eventsTable = page.locator('.hvac-events-table, table').first();
    await expect(eventsTable).toBeVisible();
    
    // Check if our event appears
    const eventRow = page.locator(`tr:has-text("${eventDetails.title}")`).first();
    const eventFound = await eventRow.count() > 0;
    
    if (eventFound) {
      console.log('✓ Event found in dashboard!');
      await actions.screenshot('tec-event-in-dashboard');
    } else {
      console.log('✗ Event not found in dashboard yet (may need approval)');
      // Check if in pending/draft status
      const allEvents = await page.locator('.hvac-events-table tbody tr').allTextContents();
      console.log('All events in table:', allEvents);
    }
    
    expect(eventFound || hasSuccessMessage).toBe(true);
  });

  test('Edit an existing event', async ({ authenticatedPage: page }) => {
    test.setTimeout(60000);
    const actions = new CommonActions(page);

    // First, navigate to dashboard to find an event to edit
    await actions.navigateAndWait('/hvac-dashboard/');
    
    // Find the first event with an Edit link
    const editLink = page.locator('a:has-text("Edit")').first();
    const hasEditableEvent = await editLink.count() > 0;
    
    if (!hasEditableEvent) {
      console.log('No editable events found, skipping edit test');
      test.skip();
      return;
    }
    
    // Click the edit link
    await editLink.click();
    await page.waitForLoadState('networkidle');
    await actions.screenshot('tec-edit-event-page');
    
    // Wait for form to load
    const titleField = page.locator('input[name="post_title"], input#post_title').first();
    await expect(titleField).toBeVisible();
    
    // Get current title
    const currentTitle = await titleField.inputValue();
    console.log('Current event title:', currentTitle);
    
    // Update the title
    const updatedTitle = `${currentTitle} - Updated ${new Date().toLocaleTimeString()}`;
    await titleField.fill(updatedTitle);
    
    // Update description if possible
    const tinyMCE = page.frameLocator('#tcepostcontent_ifr');
    const tinyMCEBody = tinyMCE.locator('body');
    if (await tinyMCEBody.count() > 0) {
      const currentContent = await tinyMCEBody.textContent();
      await tinyMCEBody.fill(`${currentContent}\n\nUpdated: ${new Date().toLocaleString()}`);
    } else {
      const contentField = page.locator('textarea[name="post_content"], textarea#tcepostcontent').first();
      if (await contentField.count() > 0) {
        const currentContent = await contentField.inputValue();
        await contentField.fill(`${currentContent}\n\nUpdated: ${new Date().toLocaleString()}`);
      }
    }
    
    await actions.screenshot('tec-edit-form-updated');
    
    // Submit the changes
    const submitButton = page.locator('input[type="submit"][name="community-event"], button[type="submit"], input.button-primary[type="submit"]').first();
    await expect(submitButton).toBeVisible();
    
    await Promise.all([
      page.waitForURL(/\/(event-updated|my-events|hvac-dashboard|manage-event)/, { timeout: 30000 }).catch(() => {}),
      page.waitForSelector('.tribe-success, .updated, .notice-success', { timeout: 30000 }).catch(() => {}),
      submitButton.click()
    ]);
    
    await actions.screenshot('tec-after-edit-submit');
    
    // Verify the update
    const successMessage = page.locator('.tribe-success, .updated, .notice-success').first();
    const hasSuccessMessage = await successMessage.count() > 0;
    
    if (hasSuccessMessage) {
      console.log('Edit success message found:', await successMessage.textContent());
    }
    
    // Go back to dashboard to verify the change
    await actions.navigateAndWait('/hvac-dashboard/');
    
    // Look for the updated event
    const updatedEventRow = page.locator(`tr:has-text("${updatedTitle}")`).first();
    const updateFound = await updatedEventRow.count() > 0;
    
    if (updateFound) {
      console.log('✓ Updated event found in dashboard!');
      await actions.screenshot('tec-updated-event-in-dashboard');
    }
    
    expect(updateFound || hasSuccessMessage).toBe(true);
  });
});