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

/**
 * AI Agent Framework - Settings E2E Tests
 *
 * Tests the module settings functionality including:
 * - Settings page navigation
 * - Settings display and editing
 * - Settings validation
 * - Settings save/reset
 *
 * Demo Credentials:
 * - Admin: admin@demo.com / password123
 */

// Helper function to login as admin
async function loginAsAdmin(page: any) {
  await page.goto('/auth/login', { waitUntil: 'networkidle' });
  await page.locator('#email').fill('admin@demo.com');
  await page.locator('#password').fill('password123');
  await page.locator('button[type="submit"]').click();
  await page.waitForURL('**/dashboard', { timeout: 15000 });
}

test.describe('Settings Page', () => {
  test.beforeEach(async ({ page }) => {
    await loginAsAdmin(page);
  });

  test('should navigate to Settings page and display page elements', async ({ page }) => {
    // Navigate to Settings page
    await page.goto('/ai-hub/agents/settings', { waitUntil: 'networkidle' });

    // Verify page loaded
    await expect(page).toHaveURL(/.*settings/);

    // Verify page heading
    await expect(page.locator('h4, h5').filter({ hasText: /Settings|Configuration/i }).first()).toBeVisible({ timeout: 10000 });
  });

  test('should display settings form with sections', async ({ page }) => {
    await page.goto('/ai-hub/agents/settings', { waitUntil: 'networkidle' });
    await page.waitForTimeout(1000);

    // Check for settings form
    const form = page.locator('form');
    await expect(form.first()).toBeVisible({ timeout: 5000 });

    // Check for settings sections (cards with settings groups)
    const settingsSections = page.locator('.card, .accordion-item').filter({ hasText: /General|Execution|Approval|Safety|Trigger/i });
    const sectionCount = await settingsSections.count();
    expect(sectionCount).toBeGreaterThanOrEqual(0);
  });

  test('should display current settings values', async ({ page }) => {
    await page.goto('/ai-hub/agents/settings', { waitUntil: 'networkidle' });
    await page.waitForTimeout(1000);

    // Check that inputs have values (not all empty)
    const inputs = page.locator('input:not([type="hidden"]), select, textarea');
    const inputCount = await inputs.count();

    if (inputCount > 0) {
      // At least some inputs should have values
      let hasValueCount = 0;
      for (let i = 0; i < Math.min(inputCount, 5); i++) {
        const value = await inputs.nth(i).inputValue().catch(() => '');
        if (value) hasValueCount++;
      }
      // Some settings should have default values
    }
  });

  test('should have save button', async ({ page }) => {
    await page.goto('/ai-hub/agents/settings', { waitUntil: 'networkidle' });
    await page.waitForTimeout(1000);

    // Find save button
    const saveButton = page.locator('button').filter({ hasText: /Save|Update|Submit/i }).first();
    await expect(saveButton).toBeVisible({ timeout: 5000 });
  });
});

test.describe('Settings - Updates', () => {
  test.beforeEach(async ({ page }) => {
    await loginAsAdmin(page);
  });

  test('should update text/number setting', async ({ page }) => {
    await page.goto('/ai-hub/agents/settings', { waitUntil: 'networkidle' });
    await page.waitForTimeout(1000);

    // Find a number input (like timeout or max actions)
    const numberInput = page.locator('input[type="number"]').first();

    if (await numberInput.isVisible().catch(() => false)) {
      const originalValue = await numberInput.inputValue();

      // Change value
      await numberInput.fill('25');
      await page.waitForTimeout(300);

      // Click save button
      const saveButton = page.locator('button').filter({ hasText: /Save|Update|Submit/i }).first();
      await saveButton.click();
      await page.waitForTimeout(2000);

      // Check for success message
      const successMessage = page.locator('.swal2-icon-success, .toast-success, .alert-success');
      // Success should appear

      // Restore original value
      await page.goto('/ai-hub/agents/settings', { waitUntil: 'networkidle' });
      await numberInput.fill(originalValue || '10');
      await saveButton.click();
    }
  });

  test('should update select dropdown setting', async ({ page }) => {
    await page.goto('/ai-hub/agents/settings', { waitUntil: 'networkidle' });
    await page.waitForTimeout(1000);

    // Find a select dropdown (like default autonomy level)
    const selectInput = page.locator('select').first();

    if (await selectInput.isVisible().catch(() => false)) {
      const options = await selectInput.locator('option').allTextContents();

      if (options.length > 1) {
        // Select a different option
        await selectInput.selectOption({ index: 1 });
        await page.waitForTimeout(300);

        // Save settings
        const saveButton = page.locator('button').filter({ hasText: /Save|Update|Submit/i }).first();
        await saveButton.click();
        await page.waitForTimeout(2000);

        // Check for success
        const successMessage = page.locator('.swal2-icon-success, .toast-success, .alert-success');
      }
    }
  });

  test('should toggle switch/checkbox setting', async ({ page }) => {
    await page.goto('/ai-hub/agents/settings', { waitUntil: 'networkidle' });
    await page.waitForTimeout(1000);

    // Find a checkbox or switch input
    const switchInput = page.locator('input[type="checkbox"], .form-switch input').first();

    if (await switchInput.isVisible().catch(() => false)) {
      const isChecked = await switchInput.isChecked();

      // Toggle the switch
      if (isChecked) {
        await switchInput.uncheck();
      } else {
        await switchInput.check();
      }
      await page.waitForTimeout(300);

      // Save settings
      const saveButton = page.locator('button').filter({ hasText: /Save|Update|Submit/i }).first();
      await saveButton.click();
      await page.waitForTimeout(2000);

      // Restore original state
      await page.goto('/ai-hub/agents/settings', { waitUntil: 'networkidle' });
      if (isChecked) {
        await switchInput.check();
      } else {
        await switchInput.uncheck();
      }
      await saveButton.click();
    }
  });
});

test.describe('Settings - Validation', () => {
  test.beforeEach(async ({ page }) => {
    await loginAsAdmin(page);
  });

  test('should validate required fields', async ({ page }) => {
    await page.goto('/ai-hub/agents/settings', { waitUntil: 'networkidle' });
    await page.waitForTimeout(1000);

    // Find a required input and clear it
    const requiredInput = page.locator('input[required]').first();

    if (await requiredInput.isVisible().catch(() => false)) {
      await requiredInput.fill('');
      await page.waitForTimeout(200);

      // Try to submit
      const saveButton = page.locator('button').filter({ hasText: /Save|Update|Submit/i }).first();
      await saveButton.click();
      await page.waitForTimeout(1000);

      // Should show validation error or HTML5 validation
      const errorMessage = page.locator('.is-invalid, .invalid-feedback, .text-danger');
      // Error indication should appear
    }
  });

  test('should validate number constraints', async ({ page }) => {
    await page.goto('/ai-hub/agents/settings', { waitUntil: 'networkidle' });
    await page.waitForTimeout(1000);

    // Find a number input with min/max constraints
    const numberInput = page.locator('input[type="number"][min], input[type="number"][max]').first();

    if (await numberInput.isVisible().catch(() => false)) {
      const min = await numberInput.getAttribute('min');
      const max = await numberInput.getAttribute('max');

      // Try entering invalid value
      if (min) {
        await numberInput.fill(String(parseInt(min) - 1));
      } else if (max) {
        await numberInput.fill(String(parseInt(max) + 1));
      }

      await page.waitForTimeout(200);

      // Try to submit
      const saveButton = page.locator('button').filter({ hasText: /Save|Update|Submit/i }).first();
      await saveButton.click();
      await page.waitForTimeout(1000);

      // Should show validation error
    }
  });
});
