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

const mockUsers = {
  data: [
    {
      id: 'u1', fullName: 'Nguyen Van A', phone: '0912345678', email: 'a@test.com',
      role: 'USER', kycStatus: 'VERIFIED', status: 'ACTIVE', createdAt: '2025-12-01T00:00:00Z',
    },
    {
      id: 'u2', fullName: 'Tran Thi B', phone: '0987654321', email: 'b@test.com',
      role: 'AGENT', kycStatus: 'PENDING', status: 'ACTIVE', createdAt: '2026-01-15T00:00:00Z',
    },
    {
      id: 'u3', fullName: 'Le Van C', phone: '0909123456', email: null,
      role: 'ADMIN', kycStatus: 'VERIFIED', status: 'LOCKED', createdAt: '2025-11-01T00:00:00Z',
    },
  ],
  total: 3, page: 1, limit: 20, totalPages: 1,
};

test.describe('Admin Users Management', () => {
  test.beforeEach(async ({ page }) => {
    await page.route('**/admin/users**', (route) => {
      if (route.request().method() === 'GET') {
        return route.fulfill({
          status: 200,
          contentType: 'application/json',
          body: JSON.stringify(mockUsers),
        });
      }
      return route.continue();
    });
  });

  test('renders user management page with table', async ({ page }) => {
    await page.goto('/admin/users');

    await expect(page.getByText('Nguyen Van A')).toBeVisible({ timeout: 10000 });
    await expect(page.getByText('Tran Thi B')).toBeVisible();
    await expect(page.getByText('Le Van C')).toBeVisible();
  });

  test('displays user roles and statuses', async ({ page }) => {
    await page.goto('/admin/users');

    await expect(page.getByText('Nguyen Van A')).toBeVisible({ timeout: 10000 });
    // Role badges
    await expect(page.getByText('AGENT').first()).toBeVisible();
    await expect(page.getByText('ADMIN').first()).toBeVisible();
  });

  test('renders search and filter controls', async ({ page }) => {
    await page.goto('/admin/users');

    // Search input should exist
    const searchInput = page.getByPlaceholder(/Tim kiem|Search/i);
    await expect(searchInput).toBeVisible({ timeout: 10000 });
  });

  test('handles empty user list', async ({ page }) => {
    await page.route('**/admin/users**', (route) =>
      route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({ data: [], total: 0, page: 1, limit: 20, totalPages: 0 }),
      }),
    );

    await page.goto('/admin/users');
    await page.waitForTimeout(2000);

    // Page should still render without crash
    await expect(page.locator('body')).toBeVisible();
  });
});
