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

test.describe('Demo Booking - Debug Issue', () => {
  test('reproduce booking submission failure', async ({ page }) => {
    // Enable console logging
    const consoleMessages: string[] = [];
    page.on('console', msg => {
      consoleMessages.push(`${msg.type()}: ${msg.text()}`);
    });

    // Track network requests
    const requests: any[] = [];
    page.on('request', request => {
      if (request.url().includes('/api/')) {
        requests.push({
          url: request.url(),
          method: request.method(),
          postData: request.postData(),
        });
      }
    });

    const responses: any[] = [];
    page.on('response', async response => {
      if (response.url().includes('/api/')) {
        const body = await response.text().catch(() => 'Could not read body');
        responses.push({
          url: response.url(),
          status: response.status(),
          body: body.substring(0, 500), // First 500 chars
        });
      }
    });

    console.log('🧪 Starting booking flow test...');

    // 1. Navigate to demo page
    console.log('1. Navigating to demo page...');
    await page.goto('http://localhost:9000/en/demo');
    await page.waitForLoadState('networkidle');

    // CRITICAL: Dismiss cookie consent banner if present
    console.log('2. Checking for cookie consent banner...');
    const acceptCookiesButton = page.getByRole('button', { name: /accept|got it/i });
    if (await acceptCookiesButton.isVisible().catch(() => false)) {
      console.log('   Dismissing cookie consent...');
      await acceptCookiesButton.click();
      await page.waitForTimeout(500);
    }

    console.log('3. Page ready. Taking screenshot...');
    await page.screenshot({ path: '/tmp/01-page-loaded.png' });

    // 2. Select duration
    console.log('3. Selecting 30 minute duration...');
    const duration30Button = page.getByRole('button', { name: /30 minutes/i });
    await duration30Button.click();
    await page.screenshot({ path: '/tmp/02-duration-selected.png' });

    // 3. Click Next to go to date/time
    console.log('4. Clicking Next...');
    const nextButton = page.getByRole('button', { name: 'Next' });
    await nextButton.click();
    await page.waitForTimeout(1000);
    await page.screenshot({ path: '/tmp/03-date-time-step.png' });

    // 4. Select a future date (tomorrow)
    console.log('5. Selecting tomorrow...');
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const dayButton = page.locator(`button[aria-label*="${tomorrow.getDate()}"]`).first();
    await dayButton.click();
    await page.waitForTimeout(500);

    // 5. Select time slot
    console.log('6. Selecting time slot 14:00...');
    const timeSlot = page.getByRole('button', { name: /14:00|2:00 PM/i }).first();
    await timeSlot.click();
    await page.screenshot({ path: '/tmp/04-time-selected.png' });

    // 6. Click Next to user info
    console.log('7. Clicking Next to user info...');
    await nextButton.click();
    await page.waitForTimeout(1000);
    await page.screenshot({ path: '/tmp/05-user-info-step.png' });

    // 7. Fill user information
    console.log('8. Filling user information...');
    await page.getByLabel(/name/i).fill('Playwright Test User');
    await page.getByLabel(/email/i).fill('playwright@test.com');
    await page.getByLabel(/phone/i).fill('+966501234567');
    await page.getByLabel(/message/i).fill('Automated Playwright test');
    await page.screenshot({ path: '/tmp/06-info-filled.png' });

    // 8. Click Next to confirmation
    console.log('9. Clicking Next to confirmation...');
    await nextButton.click();
    await page.waitForTimeout(1000);
    await page.screenshot({ path: '/tmp/07-confirmation-step.png' });

    // 9. Submit booking
    console.log('10. Clicking Confirm Booking...');
    const confirmButton = page.getByRole('button', { name: /Confirm Booking/i });

    // Wait for API response
    const responsePromise = page.waitForResponse(
      response => response.url().includes('/api/demo/book') && response.request().method() === 'POST',
      { timeout: 10000 }
    );

    await confirmButton.click();

    console.log('11. Waiting for API response...');
    const apiResponse = await responsePromise.catch(() => null);

    if (apiResponse) {
      console.log(`API Response Status: ${apiResponse.status()}`);
      const apiBody = await apiResponse.text();
      console.log(`API Response Body: ${apiBody}`);
    } else {
      console.log('❌ No API response received');
    }

    await page.waitForTimeout(3000);
    await page.screenshot({ path: '/tmp/08-after-submit.png' });

    // 10. Check what's on screen
    console.log('12. Checking page state...');
    const pageContent = await page.content();
    const hasSuccessMessage = pageContent.includes('success') || pageContent.includes('confirmed') || pageContent.includes('reference');
    const hasErrorMessage = pageContent.includes('error') || pageContent.includes('failed');

    console.log(`Has success indicators: ${hasSuccessMessage}`);
    console.log(`Has error indicators: ${hasErrorMessage}`);

    // 11. Print all console messages
    console.log('\n=== BROWSER CONSOLE MESSAGES ===');
    consoleMessages.forEach(msg => console.log(msg));

    // 12. Print all API requests/responses
    console.log('\n=== API REQUESTS ===');
    requests.forEach(req => {
      console.log(`${req.method} ${req.url}`);
      if (req.postData) {
        console.log(`Body: ${req.postData.substring(0, 200)}`);
      }
    });

    console.log('\n=== API RESPONSES ===');
    responses.forEach(res => {
      console.log(`${res.status} ${res.url}`);
      console.log(`Body: ${res.body}`);
    });

    // Fail test to show output
    expect(hasSuccessMessage).toBe(true);
  });
});
