import { STAGING_URL, PATHS, TIMEOUTS } from './config/staging-config';
import { test, expect } from '@playwright/test';

// STAGING_URL is now imported from config

test.describe('Event Debug Final', () => {
  test('debug exact event submission requirements', async ({ page }) => {
    // Enable console logging
    page.on('console', msg => {
      if (msg.type() === 'error') {
        console.log('Console error:', msg.text());
      }
    });
    
    // Login
    await page.goto(PATHS.login);
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'Test123!');
    await page.click('#wp-submit');
    await page.waitForURL('**/hvac-dashboard/');
    
    // Navigate to create event
    await page.click('a:has-text("CREATE EVENT")');
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(3000); // Ensure everything loads
    
    // Fill title
    const eventTitle = `Debug Event ${Date.now()}`;
    await page.fill('input[name="post_title"]', eventTitle);
    
    // Debug: Check what type of editor we have
    const editorInfo = await page.evaluate(() => {
      const info: any = {};
      
      // Check for TinyMCE
      if (typeof tinymce !== 'undefined') {
        info.tinymce = true;
        info.activeEditor = tinymce.activeEditor ? true : false;
        info.editorId = tinymce.activeEditor ? tinymce.activeEditor.id : null;
      }
      
      // Check for textarea
      const textarea = document.querySelector('textarea#content, textarea[name="post_content"]');
      info.textarea = textarea ? true : false;
      info.textareaVisible = textarea ? (textarea as HTMLElement).offsetParent !== null : false;
      
      // Check for iframe
      const iframe = document.querySelector('iframe[id*="content"], iframe[title*="editor"]');
      info.iframe = iframe ? true : false;
      
      return info;
    });
    console.log('Editor info:', editorInfo);
    
    // Try multiple approaches to fill description
    const description = 'This is a required description for the HVAC training event.';
    
    // Method 1: Direct TinyMCE API
    const tinymceResult = await page.evaluate((desc) => {
      if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
        tinymce.activeEditor.setContent(desc);
        // Trigger change events
        tinymce.activeEditor.fire('change');
        tinymce.activeEditor.save();
        return true;
      }
      return false;
    }, description).catch(() => false);
    console.log('TinyMCE method result:', tinymceResult);
    
    // Method 2: Fill hidden textarea
    const textareaResult = await page.evaluate((desc) => {
      const textarea = document.querySelector('textarea#content, textarea[name="post_content"]');
      if (textarea) {
        (textarea as HTMLTextAreaElement).value = desc;
        // Trigger events
        textarea.dispatchEvent(new Event('change', { bubbles: true }));
        textarea.dispatchEvent(new Event('input', { bubbles: true }));
        return true;
      }
      return false;
    }, description).catch(() => false);
    console.log('Textarea method result:', textareaResult);
    
    // Method 3: Fill iframe if visible
    try {
      const iframe = page.frameLocator('iframe[id*="content"], iframe[title*="editor"]').first();
      await iframe.locator('body').click();
      await iframe.locator('body').fill(description);
      console.log('Iframe method succeeded');
    } catch (e) {
      console.log('Iframe method failed:', e.message);
    }
    
    // Fill dates and times
    const today = new Date();
    const dateStr = `${(today.getMonth() + 1).toString().padStart(2, '0')}/${today.getDate().toString().padStart(2, '0')}/${today.getFullYear()}`;
    
    await page.fill('input#EventStartDate', dateStr);
    await page.fill('input#EventEndDate', dateStr);
    await page.fill('input#EventStartTime', '10:00 AM');
    await page.fill('input#EventEndTime', '12:00 PM');
    
    // Verify description is set before submitting
    const contentCheck = await page.evaluate(() => {
      const checks: any = {};
      
      // Check TinyMCE content
      if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
        checks.tinymceContent = tinymce.activeEditor.getContent();
      }
      
      // Check textarea value
      const textarea = document.querySelector('textarea#content, textarea[name="post_content"]');
      if (textarea) {
        checks.textareaContent = (textarea as HTMLTextAreaElement).value;
      }
      
      // Check form data
      const form = document.querySelector('form');
      if (form) {
        const formData = new FormData(form as HTMLFormElement);
        checks.formData = {};
        formData.forEach((value, key) => {
          checks.formData[key] = value;
        });
      }
      
      return checks;
    });
    console.log('Content check before submit:', contentCheck);
    
    // Try to find and click the submit button
    await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
    await page.waitForTimeout(1000);
    
    // Debug: Check all submit buttons
    const submitButtons = await page.evaluate(() => {
      const buttons = document.querySelectorAll('input[type="submit"], button[type="submit"]');
      return Array.from(buttons).map(btn => ({
        value: (btn as HTMLInputElement).value || btn.textContent,
        name: (btn as HTMLInputElement).name,
        id: btn.id,
        visible: (btn as HTMLElement).offsetParent !== null
      }));
    });
    console.log('Submit buttons found:', submitButtons);
    
    // Click the submit button
    const submitButton = page.locator('input[type="submit"][value="Submit Event"]');
    
    // Listen for network activity
    page.on('request', request => {
      if (request.method() === 'POST') {
        console.log('POST request:', request.url());
      }
    });
    
    page.on('response', response => {
      if (response.status() >= 400) {
        console.log('Error response:', response.status(), response.url());
      }
    });
    
    // Submit form
    await submitButton.click();
    console.log('Clicked submit');
    
    // Wait and check result
    await page.waitForTimeout(5000);
    
    // Final check
    const finalUrl = page.url();
    const finalContent = await page.content();
    
    console.log('Final URL:', finalUrl);
    
    // Look for any messages
    const messages = await page.evaluate(() => {
      const msgs: string[] = [];
      // Check for any error or success divs
      const elements = document.querySelectorAll('.error, .notice, .updated, .message, .tribe-error, .tribe-success');
      elements.forEach(el => {
        if (el.textContent) {
          msgs.push(el.textContent.trim());
        }
      });
      return msgs;
    });
    console.log('Messages found:', messages);
    
    // Check if form is still present
    const formStillPresent = await page.locator('form').count() > 0;
    console.log('Form still present:', formStillPresent);
    
    // Save debug info
    await page.screenshot({ path: 'test-results/event-debug-final.png', fullPage: true });
    
    // For now, just pass the test to see debug output
    expect(true).toBe(true);
  });
});