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

/**
 * Debug Event Creation - Updated for TEC Community Events
 * 
 * This test helps debug issues with The Events Calendar Community Events form
 * after removing the HVAC custom override.
 */
test.describe('Debug Event Creation - TEC', () => {
  test('Create event with TEC form and verify dashboard', 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-loaded');
    
    // Wait for the form to be fully loaded
    await page.waitForLoadState('networkidle');
    
    // Debug: Check page content
    const pageTitle = await page.title();
    console.log('Page title:', pageTitle);
    
    // Check what's on the page
    const pageContent = await page.locator('body').innerText();
    console.log('Page content preview (first 500 chars):', pageContent.substring(0, 500));
    
    // Look for TEC Community Events form indicators
    const formSelectors = [
      'form#tribe-community-events',
      'form.tribe-community-events-form',
      'form[action*="community-events"]',
      'form#event-community-form'
    ];
    
    let formFound = false;
    let formSelector = '';
    
    for (const selector of formSelectors) {
      const form = page.locator(selector);
      if (await form.count() > 0) {
        formFound = true;
        formSelector = selector;
        console.log(`✓ Found form with selector: ${selector}`);
        break;
      }
    }
    
    // If no form found, check for the raw shortcode
    if (!formFound) {
      const hasRawShortcode = pageContent.includes('[tribe_community_events');
      if (hasRawShortcode) {
        console.log('ERROR: Shortcode not processed - TEC Community Events may not be properly initialized');
        throw new Error('TEC Community Events shortcode not processed');
      }
    }
    
    // Try to find any form on the page
    if (!formFound) {
      const anyForm = await page.locator('form').count();
      console.log(`Found ${anyForm} form(s) on the page`);
      
      if (anyForm > 0) {
        // List all forms
        const forms = await page.locator('form').all();
        for (let i = 0; i < forms.length; i++) {
          const id = await forms[i].getAttribute('id');
          const className = await forms[i].getAttribute('class');
          const action = await forms[i].getAttribute('action');
          console.log(`Form ${i + 1}: id="${id}", class="${className}", action="${action}"`);
        }
      }
    }
    
    // Check for title fields
    const titleSelectors = [
      'input[name="post_title"]',
      'input#post_title',
      'input[name="EventTitle"]',
      'input[placeholder*="title" i]'
    ];
    
    let titleField = null;
    for (const selector of titleSelectors) {
      const field = page.locator(selector).first();
      if (await field.count() > 0) {
        titleField = field;
        console.log(`✓ Found title field with selector: ${selector}`);
        break;
      }
    }
    
    if (!titleField) {
      // List all input fields on the page for debugging
      const inputs = await page.locator('input[type="text"], input:not([type])').all();
      console.log(`Found ${inputs.length} text input fields`);
      
      for (let i = 0; i < Math.min(inputs.length, 10); i++) {
        const name = await inputs[i].getAttribute('name');
        const id = await inputs[i].getAttribute('id');
        const placeholder = await inputs[i].getAttribute('placeholder');
        console.log(`Input ${i + 1}: name="${name}", id="${id}", placeholder="${placeholder}"`);
      }
      
      throw new Error('Could not find event title field');
    }
    
    // Create a unique event name
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const eventTitle = `TEC Debug Event ${timestamp}`;
    
    // Fill in the event title
    await titleField.fill(eventTitle);
    console.log('✓ Filled event title:', eventTitle);
    await actions.screenshot('tec-title-filled');
    await actions.screenshot('event-title-filled');
    
    // Fill in event description
    const descriptionText = `This is a test event created to debug the TEC event creation process.
    
Test Event Details:
- Event Title: ${eventTitle}
- Created: ${new Date().toLocaleString()}
- Purpose: Testing The Events Calendar Community Events form`;

    try {
      // Try TinyMCE editor first
      const editorFrame = page.frameLocator('iframe[id*="_ifr"]').first();
      if (await editorFrame.locator('body').count() > 0) {
        await editorFrame.locator('body').fill(descriptionText);
        console.log('✓ Filled TinyMCE editor');
      } else {
        throw new Error('TinyMCE not found');
      }
    } catch (e) {
      // Fallback to textarea
      const textareaSelectors = [
        'textarea[name="post_content"]',
        'textarea#tcepostcontent',
        'textarea#content',
        'textarea[name="event_description"]',
        'textarea.wp-editor-area'
      ];
      
      let filled = false;
      for (const selector of textareaSelectors) {
        const field = page.locator(selector).first();
        if (await field.count() > 0 && await field.isVisible()) {
          await field.fill(descriptionText);
          console.log(`✓ Filled description using selector: ${selector}`);
          filled = true;
          break;
        }
      }
      
      if (!filled) {
        console.log('Warning: Could not find description field');
      }
    }
    
    // Set event dates (look for date fields)
    const dateSelectors = {
      startDate: [
        'input[name="EventStartDate"]',
        'input#EventStartDate',
        'input[name="event_start_date"]',
        'input[name="EventDate"]'
      ],
      endDate: [
        'input[name="EventEndDate"]',
        'input#EventEndDate',
        'input[name="event_end_date"]'
      ],
      startTime: [
        'input[name="EventStartTime"]',
        'input#EventStartTime',
        'select[name="EventStartTime"]'
      ],
      endTime: [
        'input[name="EventEndTime"]',
        'input#EventEndTime',
        'select[name="EventEndTime"]'
      ]
    };
    
    // Generate date 7 days from now
    const futureDate = new Date();
    futureDate.setDate(futureDate.getDate() + 7);
    const dateStr = futureDate.toISOString().split('T')[0]; // YYYY-MM-DD format
    
    // Try to fill start date
    let startDateFilled = false;
    for (const selector of dateSelectors.startDate) {
      const field = page.locator(selector).first();
      if (await field.count() > 0 && await field.isVisible()) {
        await field.fill(dateStr);
        console.log(`✓ Filled start date using selector: ${selector}`);
        startDateFilled = true;
        break;
      }
    }
    
    if (!startDateFilled) {
      console.log('Warning: Could not find start date field');
    }
    
    // Try to fill end date
    let endDateFilled = false;
    for (const selector of dateSelectors.endDate) {
      const field = page.locator(selector).first();
      if (await field.count() > 0 && await field.isVisible()) {
        await field.fill(dateStr);
        console.log(`✓ Filled end date using selector: ${selector}`);
        endDateFilled = true;
        break;
      }
    }
    
    // Try to fill time fields
    for (const selector of dateSelectors.startTime) {
      const field = page.locator(selector).first();
      if (await field.count() > 0 && await field.isVisible()) {
        const tagName = await field.evaluate(el => el.tagName.toLowerCase());
        if (tagName === 'select') {
          // For select dropdown, try to select a morning time
          await field.selectOption({ index: 9 }); // Typically 9:00 AM
        } else {
          await field.fill('09:00 AM');
        }
        console.log(`✓ Filled start time using selector: ${selector}`);
        break;
      }
    }
    
    for (const selector of dateSelectors.endTime) {
      const field = page.locator(selector).first();
      if (await field.count() > 0 && await field.isVisible()) {
        const tagName = await field.evaluate(el => el.tagName.toLowerCase());
        if (tagName === 'select') {
          // For select dropdown, try to select an afternoon time
          await field.selectOption({ index: 17 }); // Typically 5:00 PM
        } else {
          await field.fill('05:00 PM');
        }
        console.log(`✓ Filled end time using selector: ${selector}`);
        break;
      }
    }
    
    // Fill venue information (optional but useful)
    const venueSelectors = {
      name: ['input[name="venue[Venue]"]', 'input#venue-venue', 'input[name="VenueName"]'],
      address: ['input[name="venue[Address]"]', 'input#venue-address', 'input[name="VenueAddress"]'],
      city: ['input[name="venue[City]"]', 'input#venue-city', 'input[name="VenueCity"]'],
      state: ['input[name="venue[State]"]', 'input#venue-state', 'select[name="venue[State]"]'],
      zip: ['input[name="venue[Zip]"]', 'input#venue-zip', 'input[name="VenueZip"]']
    };
    
    // Try to fill venue name
    for (const selector of venueSelectors.name) {
      const field = page.locator(selector).first();
      if (await field.count() > 0 && await field.isVisible()) {
        await field.fill('HVAC Test Training Center');
        console.log(`✓ Filled venue name using selector: ${selector}`);
        break;
      }
    }
    
    // Try to fill venue city
    for (const selector of venueSelectors.city) {
      const field = page.locator(selector).first();
      if (await field.count() > 0 && await field.isVisible()) {
        await field.fill('Dallas');
        console.log(`✓ Filled venue city using selector: ${selector}`);
        break;
      }
    }
    
    await actions.screenshot('form-filled-before-submit');
    
    // Look for submit button
    const submitSelectors = [
      'input[type="submit"][name="community-event"]',
      'button[type="submit"]',
      'input[type="submit"]',
      '.tribe-submit-button',
      'input.button-primary[type="submit"]',
      'button.tribe-button'
    ];
    
    let submitButton = null;
    for (const selector of submitSelectors) {
      const button = page.locator(selector).first();
      if (await button.count() > 0 && await button.isVisible()) {
        submitButton = button;
        console.log(`✓ Found submit button with selector: ${selector}`);
        break;
      }
    }
    
    if (!submitButton) {
      // List all buttons/submit inputs for debugging
      const buttons = await page.locator('button, input[type="submit"]').all();
      console.log(`Found ${buttons.length} buttons/submit inputs on page`);
      for (let i = 0; i < Math.min(buttons.length, 5); i++) {
        const type = await buttons[i].getAttribute('type');
        const text = await buttons[i].textContent();
        const value = await buttons[i].getAttribute('value');
        console.log(`Button ${i + 1}: type="${type}", text="${text}", value="${value}"`);
      }
      throw new Error('Submit button not found');
    }
    
    console.log('Clicking submit button...');
    
    // Click submit and wait for response
    await Promise.all([
      page.waitForResponse(response => 
        response.url().includes('wp-admin/admin-ajax.php') || 
        response.url().includes('manage-event') ||
        response.url().includes('tribe_events') ||
        response.url().includes('community-events'),
        { timeout: 30000 }
      ).catch(() => console.log('No AJAX/form response detected')),
      submitButton.click()
    ]);
    
    // Wait for navigation or success message
    await page.waitForTimeout(3000); // Give it time to process
    
    await actions.screenshot('after-submit');
    
    // Check if we were redirected to the event page
    const currentUrl = page.url();
    console.log('Current URL after submit:', currentUrl);
    
    // Check for success messages
    const successSelectors = [
      '.tribe-success',
      '.notice-success',
      '.updated',
      '.success',
      'text=successfully',
      'text=pending review',
      'text=submitted'
    ];
    
    let successFound = false;
    for (const selector of successSelectors) {
      const element = page.locator(selector).first();
      if (await element.count() > 0) {
        successFound = true;
        const message = await element.textContent();
        console.log(`✓ Success indicator found (${selector}): ${message}`);
        break;
      }
    }
    
    // Check for error messages
    const errorSelectors = [
      '.tribe-error',
      '.notice-error',
      '.error',
      'text=error',
      'text=failed'
    ];
    
    for (const selector of errorSelectors) {
      const element = page.locator(selector).first();
      if (await element.count() > 0) {
        const message = await element.textContent();
        console.log(`✗ Error found: ${message}`);
      }
    }
    
    // Now navigate to dashboard and check if event appears
    await actions.navigateAndWait('/hvac-dashboard/');
    await actions.screenshot('dashboard-after-event-creation');
    
    // Look for the event in the table
    const eventInTable = await page.locator(`td:has-text("${eventTitle}")`).count() > 0;
    console.log('Event found in dashboard table:', eventInTable);
    
    if (!eventInTable) {
      // Check different status filters
      console.log('Event not immediately visible, checking filters...');
      
      const filters = ['pending', 'draft', 'all'];
      for (const filter of filters) {
        const filterLink = page.locator(`a:has-text("${filter}")`).first();
        if (await filterLink.count() > 0) {
          await filterLink.click();
          await page.waitForTimeout(1000);
          
          const found = await page.locator(`td:has-text("${eventTitle}")`).count() > 0;
          if (found) {
            console.log(`✓ Event found under ${filter} filter`);
            break;
          }
        }
      }
      
      // Get all event names from the table for debugging
      const eventRows = await page.locator('.hvac-events-table tbody tr, table tbody tr').all();
      console.log(`Total events in table: ${eventRows.length}`);
      
      if (eventRows.length > 0) {
        console.log('First few events in table:');
        for (let i = 0; i < Math.min(eventRows.length, 3); i++) {
          const text = await eventRows[i].textContent();
          console.log(`  ${i + 1}: ${text?.substring(0, 100)}...`);
        }
      }
    }
    
    // Also check the event count
    const statSelectors = [
      '.hvac-stat-card:has-text("Total Events") .metric-value',
      '.stat-value:has-text("Total Events") + .stat-number',
      '.dashboard-stat:has-text("Total Events") .stat-value'
    ];
    
    for (const selector of statSelectors) {
      const element = page.locator(selector).first();
      if (await element.count() > 0) {
        const totalEvents = await element.textContent();
        console.log(`Total events count: ${totalEvents}`);
        break;
      }
    }
    
    // Test passes if we found success message OR event in table
    const testPassed = successFound || eventInTable;
    if (!testPassed) {
      console.log('\n=== TEST SUMMARY ===');
      console.log(`Event submitted: ${successFound ? 'Yes' : 'No/Unknown'}`);
      console.log(`Event in dashboard: ${eventInTable ? 'Yes' : 'No'}`);
      console.log(`Event title: ${eventTitle}`);
      console.log('===================\n');
    }
    
    expect(testPassed).toBe(true);
  });
});