/**
 * User List Management Test
 * 
 * Tags: @user_mgmt @p2 @regression @ui
 * 
 * Comprehensive functional testing of user management:
 * - User creation, editing, searching
 * - User stores and sellers management
 * - Table filtering and search
 * - Modal interactions
 */

import { test, expect } from '@playwright/test';
import { printTestCase, printSuccess, printWarning, waitForDataTable, ensureAuthenticated } from '../../helpers/test-helpers';

test.describe('03_User_Management - User List', () => {
  // Use authenticated state for all tests in this suite
  test.use({ storageState: 'auth.json' });

  const testUserName = `Test User ${Date.now()}`;
  const testUsername = `testuser_${Date.now()}@test.com`;
  
  let createdUserId: string | null = null;

  test.beforeEach(async ({ page }) => {
    // Ensure we're authenticated before navigating anywhere
    await ensureAuthenticated(page);
    
    console.log('\n🚀 Navigating to users page...');
    await page.goto('/users');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#usersTable', 20000);
    console.log('✅ Users page loaded');
  });

  test.afterEach(async ({ page }) => {
    // Cleanup: Delete test user if created
    if (createdUserId) {
      try {
        await page.goto('/users');
        await page.waitForLoadState('load');
        // Note: Deletion would need to be implemented based on actual UI
        console.log(`⚠ Test user cleanup needed: ${createdUserId}`);
      } catch (e) {
        console.log(`⚠ Could not clean up test user: ${e}`);
      }
    }
  });

  test('Test Case 1: Navigate to users page and verify structure', async ({ page }) => {
    printTestCase(1, 'Navigate to Users Page and Verify Structure');
    
    const currentUrl = page.url();
    expect(currentUrl).toContain('/users');
    expect(currentUrl).not.toContain('/login');
    printSuccess('Users page accessible');
    
    const heading = page.locator('h5.card-title:has-text("User Management")');
    await expect(heading).toBeVisible();
    printSuccess('User Management heading visible');
    
    // Verify users table exists
    const usersTable = page.locator('#usersTable');
    await expect(usersTable).toBeVisible();
    printSuccess('Users table visible');
    
    // Verify new sections exist
    const userStoresCard = page.locator('.user-stores-card');
    const userSellersCard = page.locator('.user-sellers-card');
    
    if (await userStoresCard.count() > 0) {
      printSuccess('User Stores section found');
    }
    
    if (await userSellersCard.count() > 0) {
      printSuccess('User Sellers section found');
    }
  });

  test('Test Case 2: Test users table structure', async ({ page }) => {
    printTestCase(2, 'Test Users Table Structure');
    
    const usersTable = page.locator('#usersTable');
    await expect(usersTable).toBeVisible();
    
    // Verify table headers
    const expectedHeaders = ['Name', 'Username', 'Role', 'Created at', 'Action'];
    for (const header of expectedHeaders) {
      const headerElement = usersTable.locator(`th:has-text("${header}")`);
      if (await headerElement.count() > 0) {
        printSuccess(`Header "${header}" found`);
      } else {
        printWarning(`Header "${header}" not visible`);
      }
    }
    
    // Verify table has rows
    const rows = usersTable.locator('tbody tr');
    const rowCount = await rows.count();
    expect(rowCount).toBeGreaterThan(0);
    printSuccess(`Users table has ${rowCount} rows`);
  });

  test('Test Case 3: Test search functionality', async ({ page }) => {
    printTestCase(3, 'Test Search Functionality');
    
    const searchInput = page.locator('#usersTableSearch');
    await expect(searchInput).toBeVisible();
    printSuccess('Search input visible');
    
    // Get initial row count
    const usersTable = page.locator('#usersTable');
    const initialRows = await usersTable.locator('tbody tr').count();
    console.log(`✓ Initial row count: ${initialRows}`);
    
    // Perform search
    await searchInput.fill('admin');
    await page.waitForTimeout(1000); // Wait for search to filter
    
    const filteredRows = await usersTable.locator('tbody tr:visible').count();
    console.log(`✓ Filtered row count: ${filteredRows}`);
    
    // Clear search
    await searchInput.clear();
    await page.waitForTimeout(1000);
    
    const clearedRows = await usersTable.locator('tbody tr').count();
    expect(clearedRows).toBeGreaterThan(0);
    printSuccess('Search functionality works');
  });

  test('Test Case 4: Test create user modal opens', async ({ page }) => {
    printTestCase(4, 'Test Create User Modal Opens');
    
    const createButton = page.locator('button:has-text("Create New User")');
    await expect(createButton).toBeVisible();
    await createButton.click();
    
    // Wait for modal to appear - use more flexible selectors
    const modal = page.locator('dialog:visible, .modal:visible, [role="dialog"]:visible').first();
    await expect(modal).toBeVisible({ timeout: 5000 });
    printSuccess('Create user modal opened');
    
    // Verify modal title
    const modalTitle = modal.locator('h1, h2, h3, h4, h5, h6').filter({ hasText: /Create.*User/i }).first();
    await expect(modalTitle).toBeVisible();
    printSuccess('Modal title visible');
    
    // Verify form fields exist - use more flexible selectors based on labels
    const fullnameInput = modal.getByLabel(/Full\s*Name/i).or(modal.locator('input[name*="fullname" i], input[placeholder*="name" i]').first());
    const usernameInput = modal.getByLabel(/Username/i).or(modal.locator('input[name*="username" i], input[placeholder*="username" i]').first());
    const roleSelect = modal.getByLabel(/Role/i).or(modal.locator('select[name*="role" i]').first());
    
    await expect(fullnameInput).toBeVisible();
    await expect(usernameInput).toBeVisible();
    await expect(roleSelect).toBeVisible();
    printSuccess('All form fields visible');
    
    // Close modal
    const closeButton = modal.locator('button.btn-close');
    await closeButton.click();
    await page.waitForTimeout(500);
  });

  test('Test Case 5: Test user row selection and details', async ({ page }) => {
    printTestCase(5, 'Test User Row Selection and Details');
    
    const usersTable = page.locator('#usersTable');
    const firstRow = usersTable.locator('tbody tr.user-row').first();
    
    if (await firstRow.count() > 0) {
      // Click on user row
      await firstRow.click();
      await page.waitForTimeout(1000);
      
      // Check if stores/sellers sections update
      const userStoresCard = page.locator('.user-stores-card');
      const userSellersCard = page.locator('.user-sellers-card');
      
      if (await userStoresCard.count() > 0) {
        printSuccess('User stores section responds to user selection');
      }
      
      if (await userSellersCard.count() > 0) {
        printSuccess('User sellers section responds to user selection');
      }
    } else {
      printWarning('No user rows available to test selection');
    }
  });

  test('Test Case 6: Test user stores section', async ({ page }) => {
    printTestCase(6, 'Test User Stores Section');
    
    const userStoresCard = page.locator('.user-stores-card');
    
    if (await userStoresCard.count() > 0) {
      printSuccess('User stores card found');
      
      // Check for stores table
      const storesTable = page.locator('#userStoresTable');
      if (await storesTable.count() > 0) {
        printSuccess('User stores table found');
        
        // Check if table has DataTable functionality
        const isDataTable = await page.evaluate(() => {
          return (window as any).$.fn.DataTable.isDataTable('#userStoresTable');
        });
        
        if (isDataTable) {
          printSuccess('Stores table is a DataTable');
        }
      }
      
      // Check for collapse toggle
      const collapseToggle = userStoresCard.locator('#collapseStoresToggleBtn');
      if (await collapseToggle.count() > 0) {
        printSuccess('Stores collapse toggle found');
      }
    } else {
      printWarning('User stores section not found');
    }
  });

  test('Test Case 7: Test user sellers section', async ({ page }) => {
    printTestCase(7, 'Test User Sellers Section');
    
    const userSellersCard = page.locator('.user-sellers-card');
    
    if (await userSellersCard.count() > 0) {
      printSuccess('User sellers card found');
      
      // Check for sellers table
      const sellersTable = page.locator('#userSellersTable');
      if (await sellersTable.count() > 0) {
        printSuccess('User sellers table found');
        
        // Check if table has DataTable functionality
        const isDataTable = await page.evaluate(() => {
          return (window as any).$.fn.DataTable.isDataTable('#userSellersTable');
        });
        
        if (isDataTable) {
          printSuccess('Sellers table is a DataTable');
        }
      }
      
      // Check for collapse toggle
      const collapseToggle = userSellersCard.locator('#collapseSellersToggleBtn');
      if (await collapseToggle.count() > 0) {
        printSuccess('Sellers collapse toggle found');
      }
    } else {
      printWarning('User sellers section not found');
    }
  });

  test('Test Case 8: Test edit user button', async ({ page }) => {
    printTestCase(8, 'Test Edit User Button');
    
    const usersTable = page.locator('#usersTable');
    const firstRow = usersTable.locator('tbody tr').first();
    
    if (await firstRow.count() > 0) {
      const editButton = firstRow.locator('button.btnEdit');
      
      if (await editButton.count() > 0) {
        await editButton.click();
        
        const modal = page.locator('#formUserModal');
        await expect(modal).toBeVisible({ timeout: 5000 });
        printSuccess('Edit user modal opened');
        
        // Verify modal is in edit mode
        const modalTitle = modal.locator('#formUserModalLabel');
        const titleText = await modalTitle.textContent();
        
        if (titleText && (titleText.includes('Edit') || titleText.includes('Update'))) {
          printSuccess('Modal is in edit mode');
        }
        
        // Verify form is pre-populated
        const fullnameInput = modal.locator('#inputFullname');
        const fullnameValue = await fullnameInput.inputValue();
        
        if (fullnameValue && fullnameValue.length > 0) {
          printSuccess('Form fields are pre-populated');
        }
        
        // Close modal
        const closeButton = modal.locator('button.btn-close');
        await closeButton.click();
        await page.waitForTimeout(500);
      } else {
        printWarning('Edit button not found');
      }
    } else {
      printWarning('No users available to test edit functionality');
    }
  });

  test('Test Case 9: Test form validation', async ({ page }) => {
    printTestCase(9, 'Test Form Validation');
    
    const createButton = page.locator('button.btnAdd:has-text("Create New User")');
    await createButton.click();
    
    const modal = page.locator('#formUserModal');
    await expect(modal).toBeVisible({ timeout: 5000 });
    
    // Try to submit empty form
    const saveButton = modal.locator('button[type="submit"]');
    await saveButton.click();
    await page.waitForTimeout(1000);
    
    // Check if form validation prevents submission
    // (Modal should still be visible if validation failed)
    const modalStillVisible = await modal.isVisible();
    if (modalStillVisible) {
      printSuccess('Form validation prevents empty submission');
    }
    
    // Close modal
    const closeButton = modal.locator('button.btn-close');
    await closeButton.click();
    await page.waitForTimeout(500);
  });

  test('Test Case 10: Test responsive layout', async ({ page }) => {
    printTestCase(10, 'Test Responsive Layout');
    
    // Test mobile viewport
    await page.setViewportSize({ width: 375, height: 667 });
    await page.waitForTimeout(500);
    
    const usersTable = page.locator('#usersTable');
    await expect(usersTable).toBeVisible();
    printSuccess('Users table visible on mobile');
    
    // Test tablet viewport
    await page.setViewportSize({ width: 768, height: 1024 });
    await page.waitForTimeout(500);
    
    await expect(usersTable).toBeVisible();
    printSuccess('Users table visible on tablet');
    
    // Restore desktop viewport
    await page.setViewportSize({ width: 1280, height: 720 });
    await page.waitForTimeout(500);
  });
});
