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

test.describe('Company Info Form Testing', () => {
  test('should submit company info form and save data to database', async ({ page }) => {
    // Setup: Inject localStorage data to simulate user being on Step 3
    await page.goto('http://localhost:9000/en/signup/company-info');

    // Inject signup data into localStorage
    await page.evaluate(() => {
      const signupData = {
        email: 'realtest@mawidi.com', // Use existing user from DB
        fullName: 'Real Test User',
        plan: 'tier2',
        billingPeriod: 'monthly',
        currency: 'GBP',
        createdAt: new Date().toISOString(),
        verified: true
      };
      localStorage.setItem('mawidi-signup-flow', JSON.stringify(signupData));
    });

    // Reload to pick up localStorage data
    await page.reload();
    await page.waitForLoadState('networkidle');

    // Fill the form
    await page.fill('input[placeholder="Company Name"]', 'Test Dental Clinic');
    await page.selectOption('select:near(:text("Industry"))', { label: 'Dental Clinics' });
    await page.selectOption('select:near(:text("Company Size"))', { label: '51-200 employees' });
    await page.selectOption('select:near(:text("Country"))', { label: 'Qatar' });
    await page.fill('input[placeholder="Phone Number"]', '55565656');

    // Select services
    await page.check('input[type="checkbox"]:near(:text("Booking Automation"))');
    await page.check('input[type="checkbox"]:near(:text("Deposits & Payments"))');

    // Fill additional fields
    await page.fill('input[placeholder="Number of agents needed"]', '2');
    await page.fill('input[placeholder="What will agents be used for?"]', 'Customer support and bookings');

    // Listen for console errors
    const consoleErrors: string[] = [];
    page.on('console', msg => {
      if (msg.type() === 'error') {
        consoleErrors.push(msg.text());
      }
    });

    // Listen for network requests
    const networkRequests: any[] = [];
    page.on('request', request => {
      if (request.url().includes('/api/onboarding/company-info')) {
        networkRequests.push({
          url: request.url(),
          method: request.method(),
          postData: request.postDataJSON()
        });
      }
    });

    const networkResponses: any[] = [];
    page.on('response', async response => {
      if (response.url().includes('/api/onboarding/company-info')) {
        const status = response.status();
        let body;
        try {
          body = await response.json();
        } catch {
          body = await response.text();
        }
        networkResponses.push({
          url: response.url(),
          status,
          body
        });
      }
    });

    // Submit the form
    await page.click('button:has-text("Continue")');

    // Wait for navigation or error
    await page.waitForTimeout(3000);

    // Output results
    console.log('\n=== CONSOLE ERRORS ===');
    console.log(JSON.stringify(consoleErrors, null, 2));

    console.log('\n=== NETWORK REQUESTS ===');
    console.log(JSON.stringify(networkRequests, null, 2));

    console.log('\n=== NETWORK RESPONSES ===');
    console.log(JSON.stringify(networkResponses, null, 2));

    // Take screenshot of result
    await page.screenshot({ path: 'company-info-test-result.png', fullPage: true });

    // Check for success or error message
    const errorMessage = await page.locator('text=/error|failed/i').first().textContent().catch(() => null);
    if (errorMessage) {
      console.log('\n=== ERROR MESSAGE ON PAGE ===');
      console.log(errorMessage);
    }

    // Report results
    if (networkResponses.length > 0) {
      const response = networkResponses[0];
      console.log('\n=== FINAL STATUS ===');
      console.log(`Status: ${response.status}`);
      console.log(`Response: ${JSON.stringify(response.body, null, 2)}`);

      // If successful, verify in database
      if (response.status === 200 && response.body.success) {
        console.log('\n✅ Form submission successful!');
      } else {
        console.log('\n❌ Form submission failed!');
      }
    } else {
      console.log('\n❌ No API request was made!');
    }
  });
});
