/**
 * E2E Test: Validation Errors
 * Tests form validation and error handling
 */

import { test, expect } from '@playwright/test';
import { navigateToBookingForm, waitForCookieConsent } from './test-helpers';

test.describe('Validation Errors', () => {
  test('should show errors for empty required fields', async ({ page }) => {
    await navigateToBookingForm(page);

    // Try to proceed without filling anything
    await page.getByRole('button', { name: 'Next' }).click();

    // Should show validation error
    await expect(page.getByText(/required|must|enter|fill/i).first()).toBeVisible();

    await page.screenshot({ path: 'test-results/screenshots/validation-empty-fields.png' });
  });

  test('should validate email format', async ({ page }) => {
    await navigateToBookingForm(page);

    await page.fill('input[name="fullName"]', 'Test User');
    await page.fill('input[name="telephone"]', '+966501234567');
    await page.fill('input[name="email"]', 'notanemail');

    await page.getByRole('button', { name: 'Next' }).click();

    // Should show email validation error
    await expect(page.getByText(/email|invalid|valid email/i)).toBeVisible({ timeout: 3000 });

    await page.screenshot({ path: 'test-results/screenshots/validation-invalid-email.png' });
  });

  test('should validate phone number minimum length', async ({ page }) => {
    await navigateToBookingForm(page);

    await page.fill('input[name="fullName"]', 'Test User');
    await page.fill('input[name="email"]', 'valid@test.com');
    await page.fill('input[name="telephone"]', '+123');

    await page.getByRole('button', { name: 'Next' }).click();

    // Should show phone validation error
    await expect(page.getByText(/phone|telephone|6 digits|invalid/i)).toBeVisible({ timeout: 3000 });

    await page.screenshot({ path: 'test-results/screenshots/validation-phone-too-short.png' });
  });

  test('should require duration selection', async ({ page }) => {
    await page.goto('/en/demo');
    await waitForCookieConsent(page);

    // Try to proceed without selecting duration
    await page.getByRole('button', { name: 'Next' }).click();

    // Should show duration error or stay on step 1
    const isOnStep1 = await page.locator('[data-step="1"]').isVisible();
    expect(isOnStep1).toBe(true);

    await page.screenshot({ path: 'test-results/screenshots/validation-no-duration.png' });
  });

  test('should require date and time selection', async ({ page }) => {
    await page.goto('/en/demo');
    await waitForCookieConsent(page);

    await page.getByRole('button', { name: /30 min/i }).click();
    await page.getByRole('button', { name: 'Next' }).click();

    await page.waitForTimeout(1000);

    // Try to proceed without selecting date/time
    await page.getByRole('button', { name: 'Next' }).click();

    // Should show error or stay on step 2
    const isOnStep2 = await page.locator('[data-step="2"]').isVisible();
    expect(isOnStep2).toBe(true);

    await page.screenshot({ path: 'test-results/screenshots/validation-no-datetime.png' });
  });

  test('should show loading state during submission', async ({ page }) => {
    await navigateToBookingForm(page);

    await page.fill('input[name="fullName"]', 'Loading Test');
    await page.fill('input[name="email"]', 'loading@test.com');
    await page.fill('input[name="telephone"]', '+966501234567');
    await page.getByRole('button', { name: 'Next' }).click();

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

    // Should show loading state
    await expect(page.getByText(/Submitting/i)).toBeVisible({ timeout: 2000 });

    // Button should be disabled
    await expect(confirmButton).toBeDisabled();

    await page.screenshot({ path: 'test-results/screenshots/loading-state.png' });

    // Wait for completion
    await page.waitForTimeout(5000);
  });

  test('should handle API error gracefully', async ({ page }) => {
    // Mock API error
    await page.route('**/api/demo/book', async (route) => {
      await route.fulfill({
        status: 500,
        contentType: 'application/json',
        body: JSON.stringify({
          error: 'Database connection failed',
        }),
      });
    });

    await navigateToBookingForm(page);

    await page.fill('input[name="fullName"]', 'API Error Test');
    await page.fill('input[name="email"]', 'error@test.com');
    await page.fill('input[name="telephone"]', '+966501234567');
    await page.getByRole('button', { name: 'Next' }).click();

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

    // Should show error message
    await expect(page.getByText(/error|failed|unable/i)).toBeVisible({ timeout: 10000 });

    await page.screenshot({ path: 'test-results/screenshots/api-error.png' });
  });

  test('should allow navigation back through steps', async ({ page }) => {
    await page.goto('/en/demo');
    await waitForCookieConsent(page);

    // Go to step 3
    await page.getByRole('button', { name: /30 min/i }).click();
    await page.getByRole('button', { name: 'Next' }).click();

    await page.waitForTimeout(1000);

    const tomorrowButton = page.locator('button:has-text("Tomorrow")').first();
    await tomorrowButton.waitFor({ state: 'visible', timeout: 10000 });
    await tomorrowButton.click();

    const enabledTime = page.locator('button:not([disabled]):not([title*="Too soon"]):has(svg)').first();
    await enabledTime.waitFor({ state: 'visible', timeout: 10000 });
    await enabledTime.click();

    await page.getByRole('button', { name: 'Next' }).click();

    // Now at step 3, go back
    const backButton = page.getByRole('button', { name: /Back/i });
    await backButton.click();

    // Should be at step 2
    await expect(page.locator('[data-step="2"]')).toBeVisible();

    await page.screenshot({ path: 'test-results/screenshots/navigation-back.png' });
  });
});
