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

export class UserManagementPage {
  readonly page: Page;
  readonly pageTitle: Locator;
  readonly createUserButton: Locator;
  readonly searchInput: Locator;
  readonly searchButton: Locator;
  readonly userTable: Locator;
  readonly editButtons: Locator;
  readonly deleteButtons: Locator;
  readonly pagination: Locator;

  constructor(page: Page) {
    this.page = page;
    this.pageTitle = page.getByRole('heading', { name: '用户管理' });
    this.createUserButton = page.getByRole('button', { name: '创建用户' });
    this.searchInput = page.getByPlaceholder('搜索用户名、昵称或邮箱...');
    this.searchButton = page.getByRole('button', { name: '搜索' });
    this.userTable = page.locator('table');
    this.editButtons = page.locator('button').filter({ hasText: '编辑' });
    this.deleteButtons = page.locator('button').filter({ hasText: '删除' });
    this.pagination = page.locator('[data-slot="pagination"]');
  }

  async goto() {
    // 直接导航到用户管理页面
    await this.page.goto('/admin/users');

    // 等待页面完全加载 - 使用更可靠的等待条件
    // 先等待domcontentloaded，然后等待表格数据加载
    await this.page.waitForLoadState('domcontentloaded');

    // 等待用户表格出现，使用更具体的等待条件
    await this.page.waitForSelector('h1:has-text("用户管理")', { state: 'visible', timeout: 15000 });

    // 等待表格数据加载完成，而不是等待所有网络请求
    await this.page.waitForSelector('table tbody tr', { state: 'visible', timeout: 20000 });

    await this.expectToBeVisible();
  }

  async expectToBeVisible() {
    // 等待页面完全加载，使用更精确的选择器
    await expect(this.pageTitle).toBeVisible({ timeout: 15000 });
    await expect(this.createUserButton).toBeVisible({ timeout: 10000 });

    // 等待至少一行用户数据加载完成
    await expect(this.userTable.locator('tbody tr').first()).toBeVisible({ timeout: 20000 });
  }

  async searchUsers(keyword: string) {
    await this.searchInput.fill(keyword);
    await this.searchButton.click();
    await this.page.waitForLoadState('networkidle');
  }

  async createUser(userData: {
    username: string;
    password: string;
    nickname?: string;
    email?: string;
    phone?: string;
    name?: string;
  }) {
    await this.createUserButton.click();

    // 填写用户表单
    await this.page.getByLabel('用户名').fill(userData.username);
    await this.page.getByLabel('密码').fill(userData.password);

    if (userData.nickname) {
      await this.page.getByLabel('昵称').fill(userData.nickname);
    }
    if (userData.email) {
      await this.page.getByLabel('邮箱').fill(userData.email);
    }
    if (userData.phone) {
      await this.page.getByLabel('手机号').fill(userData.phone);
    }
    if (userData.name) {
      await this.page.getByLabel('真实姓名').fill(userData.name);
    }

    // 提交表单 - 使用模态框中的创建按钮
    await this.page.locator('[role="dialog"]').getByRole('button', { name: '创建用户' }).click();
    await this.page.waitForLoadState('networkidle');

    // 等待用户创建结果提示 - 成功或失败
    try {
      await Promise.race([
        this.page.waitForSelector('text=创建成功', { timeout: 10000 }),
        this.page.waitForSelector('text=创建失败', { timeout: 10000 })
      ]);

      // 检查是否有错误提示
      const errorVisible = await this.page.locator('text=创建失败').isVisible().catch(() => false);
      if (errorVisible) {
        // 如果是创建失败，不需要刷新页面
        return;
      }

      // 如果是创建成功，刷新页面
      await this.page.waitForTimeout(1000);
      await this.page.reload();
      await this.page.waitForLoadState('networkidle');
      await this.expectToBeVisible();
    } catch (error) {
      // 如果没有提示出现，继续执行
      console.log('创建操作没有显示提示信息，继续执行');
      await this.page.reload();
      await this.page.waitForLoadState('networkidle');
      await this.expectToBeVisible();
    }
  }

  async getUserCount(): Promise<number> {
    const rows = await this.userTable.locator('tbody tr').count();
    return rows;
  }

  async getUserByUsername(username: string): Promise<Locator | null> {
    const userRow = this.userTable.locator('tbody tr').filter({ hasText: username }).first();
    return (await userRow.count()) > 0 ? userRow : null;
  }

  async userExists(username: string): Promise<boolean> {
    const userRow = this.userTable.locator('tbody tr').filter({ hasText: username }).first();
    return (await userRow.count()) > 0;
  }

  async editUser(username: string, updates: {
    nickname?: string;
    email?: string;
    phone?: string;
    name?: string;
  }) {
    const userRow = await this.getUserByUsername(username);
    if (!userRow) throw new Error(`User ${username} not found`);

    // 编辑按钮是图标按钮，使用按钮定位（第一个按钮是编辑，第二个是删除）
    const editButton = userRow.locator('button').first();
    await editButton.waitFor({ state: 'visible', timeout: 10000 });
    await editButton.click();

    // 等待编辑模态框出现
    await this.page.waitForSelector('[role="dialog"]', { state: 'visible', timeout: 10000 });

    // 更新字段
    if (updates.nickname) {
      await this.page.getByLabel('昵称').fill(updates.nickname);
    }
    if (updates.email) {
      await this.page.getByLabel('邮箱').fill(updates.email);
    }
    if (updates.phone) {
      await this.page.getByLabel('手机号').fill(updates.phone);
    }
    if (updates.name) {
      await this.page.getByLabel('真实姓名').fill(updates.name);
    }

    // 提交更新
    await this.page.locator('[role="dialog"]').getByRole('button', { name: '更新用户' }).click();
    await this.page.waitForLoadState('networkidle');

    // 等待操作完成
    await this.page.waitForTimeout(1000);
  }

  async deleteUser(username: string) {
    const userRow = await this.getUserByUsername(username);
    if (!userRow) throw new Error(`User ${username} not found`);

    // 删除按钮是图标按钮，使用按钮定位（第二个按钮是删除）
    const deleteButton = userRow.locator('button').nth(1);
    await deleteButton.waitFor({ state: 'visible', timeout: 10000 });
    await deleteButton.click();

    // 确认删除对话框
    await this.page.getByRole('button', { name: '删除' }).click();

    // 等待删除操作完成 - 等待成功提示或错误提示
    try {
      // 等待成功提示或错误提示出现
      await Promise.race([
        this.page.waitForSelector('text=删除成功', { timeout: 10000 }),
        this.page.waitForSelector('text=删除失败', { timeout: 10000 })
      ]);

      // 检查是否有错误提示
      const errorVisible = await this.page.locator('text=删除失败').isVisible().catch(() => false);
      if (errorVisible) {
        throw new Error('删除操作失败：前端显示删除失败提示');
      }
    } catch (error) {
      // 如果没有提示出现，继续执行（可能是静默删除）
      console.log('删除操作没有显示提示信息，继续执行');
    }

    // 刷新页面确认用户是否被删除
    await this.page.reload();
    await this.page.waitForLoadState('networkidle');
    await this.expectToBeVisible();
  }

  async expectUserExists(username: string) {
    const exists = await this.userExists(username);
    expect(exists).toBe(true);
  }

  async expectUserNotExists(username: string) {
    const exists = await this.userExists(username);
    expect(exists).toBe(false);
  }
}