/**
 * Reproduce Confirm Button Not Working Issue
 * This test will capture exactly what happens when user clicks Confirm
 */

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

test('Reproduce: Confirm button not working', async ({ page }) => {
  test.setTimeout(120000);

  // Capture ALL console messages
  const consoleLog: string[] = [];
  page.on('console', msg => {
    const text = `[${msg.type()}] ${msg.text()}`;
    consoleLog.push(text);
    console.log(text);
  });

  // Capture ALL network requests
  const networkLog: any[] = [];
  page.on('request', req => {
    networkLog.push({
      method: req.method(),
      url: req.url(),
      headers: req.headers(),
      postData: req.postData()
    });
  });

  page.on('response', async res => {
    const request = res.request();
    networkLog.push({
      status: res.status(),
      url: res.url(),
      body: await res.text().catch(() => 'unable to read')
    });
  });

  console.log('\n🔍 REPRODUCING CONFIRM BUTTON ISSUE\n');

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

  // Dismiss cookies
  console.log('Step 2: Dismiss cookie banner');
  try {
    const acceptBtn = page.getByRole('button', { name: /accept/i });
    if (await acceptBtn.isVisible({ timeout: 2000 })) {
      await acceptBtn.click();
      await page.waitForTimeout(1000);
    }
  } catch (e) {
    console.log('   No cookie banner');
  }

  await page.screenshot({ path: '/tmp/debug-01-start.png', fullPage: true });

  // Duration
  console.log('Step 3: Select 30 minutes');
  await page.getByRole('button', { name: /30 minutes/i }).click();
  await page.waitForTimeout(500);

  // Next
  console.log('Step 4: Click Next (to date/time)');
  await page.getByRole('button', { name: 'Next', exact: true }).click();
  await page.waitForTimeout(2000);
  await page.screenshot({ path: '/tmp/debug-02-datetime.png', fullPage: true });

  // Date - click tomorrow
  console.log('Step 5: Select tomorrow');
  const tomorrow = page.locator('button:has-text("Tomorrow")').first();
  await tomorrow.click();
  await page.waitForTimeout(1000);

  // Time - select first available
  console.log('Step 6: Select time slot');
  const timeSlots = page.locator('button[aria-label*="PM"]:not([disabled])');
  const firstAvailable = timeSlots.first();
  const timeText = await firstAvailable.textContent();
  console.log(`   Time: ${timeText}`);
  await firstAvailable.click();
  await page.waitForTimeout(1000);
  await page.screenshot({ path: '/tmp/debug-03-time-selected.png', fullPage: true });

  // Next
  console.log('Step 7: Click Next (to user info)');
  await page.getByRole('button', { name: 'Next', exact: true }).click();
  await page.waitForTimeout(2000);
  await page.screenshot({ path: '/tmp/debug-04-userinfo.png', fullPage: true });

  // Fill form
  console.log('Step 8: Fill user information');
  await page.locator('input[name="name"], input[placeholder*="name" i]').first().fill('Debug Test User');
  await page.locator('input[type="email"], input[placeholder*="email" i]').first().fill(`debug${Date.now()}@test.com`);
  await page.locator('input[type="tel"], input[placeholder*="phone" i]').first().fill('+966501234567');
  await page.locator('textarea, input[placeholder*="message" i]').first().fill('Debug test');
  await page.waitForTimeout(500);
  await page.screenshot({ path: '/tmp/debug-05-filled.png', fullPage: true });

  // Next to confirmation
  console.log('Step 9: Click Next (to confirmation)');
  await page.getByRole('button', { name: 'Next', exact: true }).click();
  await page.waitForTimeout(2000);
  await page.screenshot({ path: '/tmp/debug-06-confirmation.png', fullPage: true });

  // Find and inspect confirm button
  console.log('Step 10: Inspecting Confirm Booking button');
  const confirmButton = page.getByRole('button', { name: /Confirm Booking/i });
  const isVisible = await confirmButton.isVisible();
  const isEnabled = await confirmButton.isEnabled();
  const isDisabled = await confirmButton.isDisabled();

  console.log(`   Confirm button visible: ${isVisible}`);
  console.log(`   Confirm button enabled: ${isEnabled}`);
  console.log(`   Confirm button disabled: ${isDisabled}`);

  // Click confirm button
  console.log('Step 11: CLICKING CONFIRM BOOKING BUTTON');

  // Set up listeners BEFORE clicking
  const apiPromise = page.waitForResponse(
    res => res.url().includes('/api/demo/book'),
    { timeout: 15000 }
  ).catch(() => null);

  await confirmButton.click();
  console.log('   Click executed');

  // Wait for response
  await page.waitForTimeout(5000);

  const apiResponse = await apiPromise;
  if (apiResponse) {
    console.log(`\n📡 API Response received:`);
    console.log(`   Status: ${apiResponse.status()}`);
    const body = await apiResponse.json().catch(e => ({ error: 'Could not parse JSON' }));
    console.log(`   Body: ${JSON.stringify(body, null, 2)}`);
  } else {
    console.log(`\n❌ NO API RESPONSE RECEIVED`);
    console.log('   This means the API call never happened');
  }

  await page.screenshot({ path: '/tmp/debug-07-after-confirm.png', fullPage: true });

  // Check what's on screen
  console.log('\nStep 12: Checking page state');
  const currentUrl = page.url();
  const pageText = await page.textContent('body');

  const hasSuccess = pageText.includes('success') || pageText.includes('confirmed') || pageText.includes('booking reference');
  const hasError = pageText.includes('error') || pageText.includes('failed') || pageText.includes('invalid');
  const hasSubmitting = pageText.includes('Submitting') || pageText.includes('Please wait');

  console.log(`   URL: ${currentUrl}`);
  console.log(`   Has success indicators: ${hasSuccess}`);
  console.log(`   Has error indicators: ${hasError}`);
  console.log(`   Shows submitting state: ${hasSubmitting}`);

  // Print console logs from browser
  console.log('\n📋 BROWSER CONSOLE LOGS:');
  consoleLog.forEach(log => console.log(`   ${log}`));

  // Print network activity for demo/book
  console.log('\n🌐 NETWORK ACTIVITY FOR /api/demo/book:');
  const bookingRequests = networkLog.filter(item =>
    item.url && item.url.includes('/api/demo/book')
  );

  if (bookingRequests.length === 0) {
    console.log('   ❌ NO REQUESTS TO /api/demo/book');
    console.log('   This proves the API call was never made!');
  } else {
    bookingRequests.forEach(item => {
      console.log(`   ${item.method || 'Response'}: ${item.url}`);
      if (item.postData) {
        console.log(`   Data: ${item.postData.substring(0, 200)}`);
      }
      if (item.status) {
        console.log(`   Status: ${item.status}`);
      }
      if (item.body && item.body !== 'unable to read') {
        console.log(`   Body: ${item.body.substring(0, 300)}`);
      }
    });
  }

  // Save final state
  await page.screenshot({ path: '/tmp/debug-08-final.png', fullPage: true });

  console.log('\n' + '='.repeat(50));
  console.log('DIAGNOSIS:');
  console.log('='.repeat(50));

  if (!apiResponse && bookingRequests.length === 0) {
    console.log('❌ PROBLEM: API call never made');
    console.log('   Possible causes:');
    console.log('   1. Form validation failing silently');
    console.log('   2. submitBooking() not being called');
    console.log('   3. JavaScript error preventing execution');
    console.log('   4. Event handler not attached to button');
  } else if (apiResponse && apiResponse.status() !== 201) {
    console.log('❌ PROBLEM: API returned error');
    console.log(`   Status: ${apiResponse.status()}`);
  } else if (apiResponse && apiResponse.status() === 201) {
    console.log('✅ API succeeded but success page not showing');
    console.log('   Check: showSuccess state or bookingReference');
  }

  console.log('\n📸 Screenshots saved to /tmp/debug-*.png');
  console.log('🎬 Video saved to test-results/*/video.webm\n');

  // Don't fail the test - we want to see all the output
  // expect(hasSuccess).toBe(true);
});
