import { test, expect } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
import { UserManagementPage } from './pages/UserManagementPage';
import { TestDataCleanup } from './utils/TestDataCleanup';
import { TestHelpers } from './utils/TestHelpers';

test.describe('测试稳定性增强验证', () => {
  let testDataCleanup: TestDataCleanup;

  test.beforeEach(async ({ page }) => {
    testDataCleanup = new TestDataCleanup(page);
  });

  test.afterEach(async ({ page }) => {
    await testDataCleanup.cleanupAll();
  });

  test('STAB-001: 页面加载稳定性测试', async ({ page }) => {
    const loginPage = new LoginPage(page);
    const dashboardPage = new DashboardPage(page);

    await test.step('1. 测试登录页面加载稳定性', async () => {
      for (let i = 0; i < 3; i++) {
        await loginPage.goto();
        await TestHelpers.waitForPageLoad(page);
        
        const isUsernameVisible = await TestHelpers.isElementVisible(loginPage.usernameInput);
        const isPasswordVisible = await TestHelpers.isElementVisible(loginPage.passwordInput);
        const isLoginButtonVisible = await TestHelpers.isElementVisible(loginPage.loginButton);
        
        expect(isUsernameVisible).toBeTruthy();
        expect(isPasswordVisible).toBeTruthy();
        expect(isLoginButtonVisible).toBeTruthy();
        
        await page.reload();
      }
    });

    await test.step('2. 测试登录流程稳定性', async () => {
      await loginPage.goto();
      await loginPage.usernameInput.fill('admin');
      await loginPage.passwordInput.fill('admin123');
      await loginPage.loginButton.click();
      
      const navigationSuccess = await TestHelpers.waitForNavigation(page, /.*dashboard/);
      expect(navigationSuccess).toBeTruthy();
      
      await TestHelpers.waitForNetworkIdle(page);
    });

    await test.step('3. 测试Dashboard页面加载稳定性', async () => {
      for (let i = 0; i < 3; i++) {
        await page.goto('/dashboard');
        await TestHelpers.waitForPageLoad(page);
        
        const dashboardContent = page.locator('.dashboard');
        const isVisible = await TestHelpers.isElementVisible(dashboardContent);
        expect(isVisible).toBeTruthy();
        
        await page.reload();
      }
    });
  });

  test('STAB-002: 元素交互稳定性测试', async ({ page }) => {
    const loginPage = new LoginPage(page);
    const dashboardPage = new DashboardPage(page);
    const userManagementPage = new UserManagementPage(page);

    await test.step('1. 登录系统', async () => {
      await loginPage.goto();
      await loginPage.usernameInput.fill('admin');
      await loginPage.passwordInput.fill('admin123');
      await loginPage.loginButton.click();
      await TestHelpers.waitForNavigation(page, /.*dashboard/);
      await TestHelpers.waitForNetworkIdle(page);
    });

    await test.step('2. 测试按钮点击稳定性', async () => {
      await dashboardPage.navigateToUserManagement();
      await TestHelpers.waitForNetworkIdle(page);
      
      const createUserButton = userManagementPage.createUserButton;
      const clickSuccess = await TestHelpers.safeClick(createUserButton);
      expect(clickSuccess).toBeTruthy();
      
      await TestHelpers.waitForModal(page);
      const modalVisible = await TestHelpers.waitForModal(page);
      expect(modalVisible).toBeTruthy();
      
      await TestHelpers.closeModal(page);
    });

    await test.step('3. 测试表单输入稳定性', async () => {
      await userManagementPage.clickCreateUser();
      await TestHelpers.waitForModal(page);
      
      const timestamp = Date.now();
      const userData = {
        username: `stab_user_${timestamp}`,
        nickname: `稳定性测试用户${timestamp}`,
        email: `stab_${timestamp}@example.com`,
        phone: '13800138000',
        password: 'Test123!@#',
        confirmPassword: 'Test123!@#',
      };
      
      testDataCleanup.trackUser(userData.username);
      
      await userManagementPage.fillUserForm(userData);
      await userManagementPage.submitForm();
      
      const successVisible = await TestHelpers.waitForSuccessMessage(page, 5000);
      expect(successVisible).toBeTruthy();
    });
  });

  test('STAB-003: 网络请求稳定性测试', async ({ page }) => {
    const loginPage = new LoginPage(page);
    const dashboardPage = new DashboardPage(page);
    const userManagementPage = new UserManagementPage(page);

    await test.step('1. 登录系统', async () => {
      await loginPage.goto();
      await loginPage.usernameInput.fill('admin');
      await loginPage.passwordInput.fill('admin123');
      await loginPage.loginButton.click();
      await TestHelpers.waitForNavigation(page, /.*dashboard/);
      await TestHelpers.waitForNetworkIdle(page);
    });

    await test.step('2. 测试API请求重试机制', async () => {
      await dashboardPage.navigateToUserManagement();
      await TestHelpers.waitForNetworkIdle(page);
      
      const initialRowCount = await userManagementPage.getTableRowCount();
      expect(initialRowCount).toBeGreaterThanOrEqual(0);
      
      await userManagementPage.searchInput.fill('admin');
      await userManagementPage.searchButton.click();
      await TestHelpers.waitForNetworkIdle(page);
      
      const searchRowCount = await userManagementPage.getTableRowCount();
      expect(searchRowCount).toBeGreaterThanOrEqual(0);
      
      await userManagementPage.clearSearch();
      await TestHelpers.waitForNetworkIdle(page);
      
      const finalRowCount = await userManagementPage.getTableRowCount();
      expect(finalRowCount).toBeGreaterThanOrEqual(0);
    });
  });

  test('STAB-004: 等待策略稳定性测试', async ({ page }) => {
    const loginPage = new LoginPage(page);
    const dashboardPage = new DashboardPage(page);

    await test.step('1. 测试元素可见性等待', async () => {
      await loginPage.goto();
      
      const usernameVisible = await TestHelpers.waitForElementVisible(loginPage.usernameInput, 5000);
      expect(usernameVisible).toBeTruthy();
      
      const passwordVisible = await TestHelpers.waitForElementVisible(loginPage.passwordInput, 5000);
      expect(passwordVisible).toBeTruthy();
      
      const loginButtonVisible = await TestHelpers.waitForElementVisible(loginPage.loginButton, 5000);
      expect(loginButtonVisible).toBeTruthy();
    });

    await test.step('2. 测试网络空闲等待', async () => {
      await loginPage.usernameInput.fill('admin');
      await loginPage.passwordInput.fill('admin123');
      await loginPage.loginButton.click();
      
      await TestHelpers.waitForNetworkIdle(page, 10000);
      const currentUrl = page.url();
      expect(currentUrl).toContain('dashboard');
    });

    await test.step('3. 测试加载完成等待', async () => {
      await page.goto('/dashboard');
      await TestHelpers.waitForPageLoad(page, 10000);
      
      const dashboardContent = page.locator('.dashboard');
      const isVisible = await TestHelpers.isElementVisible(dashboardContent);
      expect(isVisible).toBeTruthy();
    });
  });

  test('STAB-005: 错误处理稳定性测试', async ({ page }) => {
    const loginPage = new LoginPage(page);
    const dashboardPage = new DashboardPage(page);
    const userManagementPage = new UserManagementPage(page);

    await test.step('1. 测试无效登录处理', async () => {
      await loginPage.goto();
      await loginPage.usernameInput.fill('invalid_user');
      await loginPage.passwordInput.fill('invalid_password');
      await loginPage.loginButton.click();
      await page.waitForTimeout(2000);
      
      const currentUrl = page.url();
      expect(currentUrl).toContain('login');
    });

    await test.step('2. 测试表单验证错误处理', async () => {
      await loginPage.usernameInput.fill('admin');
      await loginPage.passwordInput.fill('admin123');
      await loginPage.loginButton.click();
      await TestHelpers.waitForNavigation(page, /.*dashboard/);
      await TestHelpers.waitForNetworkIdle(page);
      
      await dashboardPage.navigateToUserManagement();
      await userManagementPage.clickCreateUser();
      await TestHelpers.waitForModal(page);
      
      await userManagementPage.submitForm();
      await page.waitForTimeout(500);
      
      const errorMessageVisible = await TestHelpers.waitForErrorMessage(page, 3000);
      expect(errorMessageVisible).toBeTruthy();
    });

    await test.step('3. 测试网络错误处理', async () => {
      await TestHelpers.closeModal(page);
      
      const timestamp = Date.now();
      const userData = {
        username: `error_test_${timestamp}`,
        nickname: `错误测试用户${timestamp}`,
        email: `error_${timestamp}@example.com`,
        phone: '13800138000',
        password: 'Test123!@#',
        confirmPassword: 'Test123!@#',
      };
      
      testDataCleanup.trackUser(userData.username);
      
      await userManagementPage.fillUserForm(userData);
      await userManagementPage.submitForm();
      
      const successVisible = await TestHelpers.waitForSuccessMessage(page, 5000);
      expect(successVisible).toBeTruthy();
    });
  });

  test('STAB-006: 重试机制稳定性测试', async ({ page }) => {
    const loginPage = new LoginPage(page);
    const dashboardPage = new DashboardPage(page);
    const userManagementPage = new UserManagementPage(page);

    await test.step('1. 登录系统', async () => {
      await loginPage.goto();
      await loginPage.usernameInput.fill('admin');
      await loginPage.passwordInput.fill('admin123');
      await loginPage.loginButton.click();
      await TestHelpers.waitForNavigation(page, /.*dashboard/);
      await TestHelpers.waitForNetworkIdle(page);
    });

    await test.step('2. 测试操作重试机制', async () => {
      await dashboardPage.navigateToUserManagement();
      await TestHelpers.waitForNetworkIdle(page);
      
      const clickResult = await TestHelpers.retryOperation(
        async () => {
          await userManagementPage.clickCreateUser();
          return true;
        },
        3,
        1000
      );
      
      expect(clickResult).toBeTruthy();
    });

    await test.step('3. 测试表单提交重试机制', async () => {
      const timestamp = Date.now();
      const userData = {
        username: `retry_test_${timestamp}`,
        nickname: `重试测试用户${timestamp}`,
        email: `retry_${timestamp}@example.com`,
        phone: '13800138000',
        password: 'Test123!@#',
        confirmPassword: 'Test123!@#',
      };
      
      testDataCleanup.trackUser(userData.username);
      
      const submitResult = await TestHelpers.retryOperation(
        async () => {
          await userManagementPage.fillUserForm(userData);
          await userManagementPage.submitForm();
          const successVisible = await TestHelpers.waitForSuccessMessage(page, 3000);
          return successVisible;
        },
        2,
        2000
      );
      
      expect(submitResult).toBeTruthy();
    });
  });
});