/**
 * Working Booking Flow Test
 * Tests the complete booking from start to success page
 */

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

test.describe('Working Booking Flow', () => {
  test('complete booking flow with success verification', async ({ page }) => {
    test.setTimeout(120000);

    console.log('🎬 Starting complete booking flow...\n');

    // Step 1: Navigate
    console.log('1️⃣ Navigating to demo page...');
    await page.goto('http://localhost:9000/en/demo', { waitUntil: 'networkidle' });
    await page.screenshot({ path: '/tmp/flow-01-initial.png', fullPage: true });

    // Step 2: Handle cookie consent (CRITICAL)
    console.log('2️⃣ Handling cookie consent...');
    try {
      // Wait for cookie banner
      const cookieBanner = await page.waitForSelector('text=/cookie/i', { timeout: 3000 }).catch(() => null);
      if (cookieBanner) {
        console.log('   Cookie banner found, dismissing...');
        // Try multiple possible button texts
        const acceptBtn = await page.getByRole('button', { name: /accept|got it|okay|close/i }).first();
        if (await acceptBtn.isVisible()) {
          await acceptBtn.click();
          await page.waitForTimeout(1000);
          console.log('   ✅ Cookie banner dismissed');
        }
      } else {
        console.log('   No cookie banner present');
      }
    } catch (e) {
      console.log('   No cookie banner or already accepted');
    }

    await page.screenshot({ path: '/tmp/flow-02-cookies-handled.png', fullPage: true });

    // Step 3: Select Duration
    console.log('3️⃣ Selecting 30 minute duration...');
    const duration30 = page.getByRole('button', { name: /30 minutes/i });
    await duration30.waitFor({ state: 'visible', timeout: 10000 });
    await duration30.click();
    await page.waitForTimeout(1000);

    // Verify selection feedback
    const feedbackText = await page.getByText(/You've selected a 30 minutes/i).isVisible();
    console.log(`   Selection feedback visible: ${feedbackText}`);

    await page.screenshot({ path: '/tmp/flow-03-duration-selected.png', fullPage: true });

    // Step 4: Click Next
    console.log('4️⃣ Proceeding to date selection...');
    const nextBtn1 = page.getByRole('button', { name: 'Next' });
    await nextBtn1.click();
    await page.waitForTimeout(2000);
    await page.screenshot({ path: '/tmp/flow-04-date-time-page.png', fullPage: true });

    // Step 5: Select Date (tomorrow or later)
    console.log('5️⃣ Selecting date (tomorrow)...');

    // Look for the "Tomorrow" label and click that date
    const tomorrowButton = page.locator('button:has-text("Tomorrow")').first();
    await tomorrowButton.waitFor({ state: 'visible', timeout: 10000 });
    await tomorrowButton.click();
    await page.waitForTimeout(2000);
    await page.screenshot({ path: '/tmp/flow-05-date-selected.png', fullPage: true });

    // Step 6: Select Time
    console.log('6️⃣ Selecting available time slot...');

    // Find an enabled time slot (green checkmark, not disabled)
    const enabledTime = page.locator('button:not([disabled]):not([title*="Too soon"]):has(svg)').first();
    await enabledTime.waitFor({ state: 'visible', timeout: 10000 });

    const timeText = await enabledTime.textContent();
    console.log(`   Selected time: ${timeText?.trim()}`);

    await enabledTime.click();
    await page.waitForTimeout(1000);
    await page.screenshot({ path: '/tmp/flow-06-time-selected.png', fullPage: true });

    // Step 7: Next to User Info
    console.log('7️⃣ Proceeding to user info...');
    const nextBtn2 = page.getByRole('button', { name: 'Next', exact: true });
    await nextBtn2.click();
    await page.waitForTimeout(2000);
    await page.screenshot({ path: '/tmp/flow-07-user-info-page.png', fullPage: true });

    // Step 8: Fill User Information
    console.log('8️⃣ Filling user information...');

    const nameField = page.getByLabel(/name/i);
    await nameField.fill('Playwright User');

    const emailField = page.getByLabel(/email/i);
    const testEmail = `playwright-${Date.now()}@test.com`;
    await emailField.fill(testEmail);

    const phoneField = page.getByLabel(/phone|telephone/i);
    await phoneField.fill('+966501234567');
    console.log('   Phone entered: +966501234567');

    const messageField = page.getByLabel(/message|requirements|comments/i);
    await messageField.fill('Automated test booking');

    await page.screenshot({ path: '/tmp/flow-08-info-filled.png', fullPage: true });

    // Step 9: Next to Confirmation
    console.log('9️⃣ Proceeding to confirmation...');
    const nextBtn3 = page.getByRole('button', { name: 'Next' });
    await nextBtn3.click();
    await page.waitForTimeout(2000);
    await page.screenshot({ path: '/tmp/flow-09-confirmation-page.png', fullPage: true });

    // Step 10: Submit Booking
    console.log('🔟 Submitting booking...');

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

    const confirmBtn = page.getByRole('button', { name: /Confirm Booking/i });
    await confirmBtn.click();

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

    const status = apiResponse.status();
    const body = await apiResponse.json().catch(() => ({}));

    console.log(`\n📡 API Response:`);
    console.log(`   Status: ${status}`);
    console.log(`   Body: ${JSON.stringify(body, null, 2)}`);

    await page.waitForTimeout(3000);
    await page.screenshot({ path: '/tmp/flow-10-after-submit.png', fullPage: true });

    // Step 11: Verify Success Page
    console.log('\n✅ Verifying success page...');

    const pageContent = await page.textContent('body');

    // Check for success indicators
    const hasBookingRef = pageContent.includes('BK-') || pageContent.includes(body.bookingId || '');
    const hasSuccess = pageContent.includes('success') || pageContent.includes('confirmed');
    const hasCalendarBtn = await page.getByText(/Add to Calendar/i).isVisible().catch(() => false);
    const hasBookAnotherBtn = await page.getByText(/Book Another/i).isVisible().catch(() => false);

    console.log(`\n📊 Success Page Checks:`);
    console.log(`   Has booking reference: ${hasBookingRef}`);
    console.log(`   Has success text: ${hasSuccess}`);
    console.log(`   Has calendar button: ${hasCalendarBtn}`);
    console.log(`   Has book another button: ${hasBookAnotherBtn}`);

    // Take final screenshot
    await page.screenshot({ path: '/tmp/flow-11-final-state.png', fullPage: true });

    // Verify database
    if (body.bookingId) {
      console.log(`\n💾 Checking database for booking ${body.bookingId}...`);

      const dbCheck = await fetch(`http://127.0.0.1:54321/rest/v1/demo_bookings?select=*&id=eq.${body.bookingId}`, {
        headers: {
          'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU',
          'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU'
        }
      });

      const dbData = await dbCheck.json();
      const inDatabase = dbData && dbData.length > 0;

      console.log(`   In database: ${inDatabase ? '✅ YES' : '❌ NO'}`);
      if (inDatabase) {
        console.log(`   Phone in DB: ${dbData[0].telephone}`);
      }

      expect(inDatabase).toBe(true);
    }

    // Main assertion
    expect(status).toBe(201);
    expect(hasSuccess || hasBookingRef).toBe(true);

    console.log('\n🎉 Test completed!');
    console.log('📸 Screenshots saved to /tmp/flow-*.png');
  });
});
