import { STAGING_URL, PATHS, TIMEOUTS } from './config/staging-config';
import { test, expect, Page } from '@playwright/test';
import * as dotenv from 'dotenv';
import { resolve } from 'path';

dotenv.config({ path: resolve(__dirname, '../../../../.env') });

test.use({
  screenshot: 'only-on-failure',
  video: 'retain-on-failure',
  trace: 'retain-on-failure',
  actionTimeout: 30000,
  timeout: 120000
});

test.describe('Verify Field Mapping Fix', () => {
  const stagingUrl = process.env.UPSKILL_STAGING_URL || 'https://upskill-staging.measurequick.com';
  
  test('verify event creation with field mapping fix', async ({ page }) => {
    const username = 'test_trainer';
    const password = 'Test123!';

    // Step 1: Direct login with correct credentials
    await page.goto(stagingUrl + '/wp-login.php', { waitUntil: 'domcontentloaded' });
    await page.fill('input[name="log"]', username);
    await page.fill('input[name="pwd"]', password);
    await page.click('input[type="submit"]');
    
    // Wait for admin login to complete
    await page.waitForURL(/wp-admin/, { timeout: 30000 });
    console.log('Logged in successfully via wp-admin');

    // Step 2: Navigate to event creation page
    await page.goto(stagingUrl + '/manage-event/', { waitUntil: 'domcontentloaded' });
    
    // Wait for form to load
    await page.waitForSelector('input[name="post_title"]', { state: 'visible', timeout: 10000 });
    console.log('Event creation form loaded');

    // Step 3: Fill all required fields
    const now = new Date();
    const uniqueTitle = `Test Event ${now.toISOString().split('.')[0].replace(/[-T:]/g, '')}`;
    
    await page.fill('input[name="post_title"]', uniqueTitle);
    console.log('Filled title:', uniqueTitle);

    // Fill dates
    const eventDate = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    const dateStr = eventDate.toISOString().split('T')[0];
    
    await page.fill('input[name="EventStartDate"]', dateStr);
    await page.fill('input[name="EventEndDate"]', dateStr);
    await page.fill('input[name="EventStartTime"]', '09:00');
    await page.fill('input[name="EventEndTime"]', '17:00');
    console.log('Filled dates');

    // Step 4: Fill description - this should be mapped by our fix
    const descriptionText = `This is a test event with our field mapping fix. Created on ${now.toISOString()}.`;
    
    // Fill the textarea directly
    try {
      await page.fill('textarea[name="tcepostcontent"]', descriptionText);
      console.log('Filled description in tcepostcontent field');
    } catch (e) {
      console.log('tcepostcontent field not found, trying alternative');
    }

    // Check if TinyMCE is present
    const tinymceFrame = page.frameLocator('iframe#tcepostcontent_ifr');
    try {
      await tinymceFrame.locator('body').fill(descriptionText);
      console.log('Filled description in TinyMCE editor');
    } catch (e) {
      console.log('TinyMCE not present or not accessible');
    }

    // Use JavaScript to ensure content is set
    await page.evaluate((content) => {
      const textarea = document.querySelector('textarea[name="tcepostcontent"]');
      if (textarea) {
        textarea.value = content;
        textarea.dispatchEvent(new Event('change', { bubbles: true }));
      }
      
      // If TinyMCE is present
      if ((window as any).tinymce) {
        const editor = (window as any).tinymce.get('tcepostcontent');
        if (editor) {
          editor.setContent(content);
        }
      }
    }, descriptionText);

    // Take screenshot before submission
    await page.screenshot({ path: 'before-submission-verify.png', fullPage: true });

    // Step 5: Submit the form
    console.log('Submitting form...');
    await page.click('input[type="submit"][value="Submit Event"]');
    
    // Wait for response
    await page.waitForLoadState('networkidle');
    
    // Step 6: Check result
    const currentUrl = page.url();
    console.log('Current URL after submission:', currentUrl);
    
    // Check for errors
    const errorExists = await page.locator('.tribe-notice-error, .error-message').isVisible().catch(() => false);
    
    if (errorExists) {
      const errorText = await page.locator('.tribe-notice-error, .error-message').textContent();
      console.error('Error found:', errorText);
      await page.screenshot({ path: 'submission-error-verify.png', fullPage: true });
      
      // Check if it's the description error
      if (errorText?.includes('Event Description is required')) {
        throw new Error('Field mapping fix failed - description still required');
      }
    }
    
    // Check for success indicators
    const pageContent = await page.content();
    
    if (currentUrl.includes('/events/') || 
        currentUrl.includes('event=') ||
        pageContent.includes('Event submitted') ||
        pageContent.includes(uniqueTitle)) {
      console.log('Event created successfully!');
      console.log('Field mapping fix is working correctly');
    } else {
      // Try to find the event in the list
      await page.goto(stagingUrl + '/my-events/', { waitUntil: 'domcontentloaded' });
      await page.waitForTimeout(2000);
      
      const eventFound = await page.locator(`text="${uniqueTitle}"`).isVisible().catch(() => false);
      
      if (eventFound) {
        console.log('Event found in My Events list - creation was successful');
        console.log('Field mapping fix is working correctly');
      } else {
        throw new Error('Event creation uncertain - could not verify success');
      }
    }
  });
});