/**
 * Seller Groups Management Test
 * 
 * Tags: @admin @p2 @regression @ui
 * 
 * Comprehensive functional testing of seller groups management:
 * - Seller group CRUD operations (Create, Read, Update, Delete)
 * - Seller group shortcode validation
 * - Company assignments and management
 * - Status management and toggling
 * - Statistics and reporting
 */

import { test, expect } from '@playwright/test';
import { printTestCase, printSuccess, printWarning, waitForDataTable, ensureAuthenticated } from '../../helpers/test-helpers';

test.describe('04_Partner_Management - Seller Groups Management', () => {
  // Use authenticated state for all tests in this suite
  test.use({ storageState: 'auth.json' });

  const testGroupName = `Test Seller Group ${Date.now()}`;
  const testGroupShortcode = `TSG${Date.now().toString().slice(-6)}`;
  
  let createdGroupId: string | null = null;

  test.beforeEach(async ({ page }) => {
    // Ensure we're authenticated before navigating anywhere
    await ensureAuthenticated(page);
    
    console.log('\n🚀 Navigating to seller groups management page...');
    await page.goto('/seller-groups-management/seller-groups');
    await page.waitForLoadState('load');
    console.log('✅ Seller groups management page loaded');
  });

  test.afterEach(async ({ page }) => {
    // Cleanup: Delete test seller group if created
    if (createdGroupId) {
      try {
        await page.goto('/seller-groups-management/seller-groups');
        await page.waitForLoadState('load');
        await waitForDataTable(page, '#sellerGroupsTable', 10000);
        
        // Look for test seller group and delete it
        const testGroupRow = page.locator(`#sellerGroupsTable tr:has-text("${testGroupName}")`);
        if (await testGroupRow.count() > 0) {
          const deleteBtn = testGroupRow.locator('button:has-text("Delete"), button:has-text("Remove")');
          if (await deleteBtn.count() > 0) {
            await deleteBtn.click();
            await page.waitForTimeout(1000);
            
            // Confirm deletion if modal appears
            const confirmBtn = page.locator('.swal2-confirm, button:has-text("Yes"), button:has-text("Confirm")');
            if (await confirmBtn.count() > 0) {
              await confirmBtn.click();
              await page.waitForTimeout(2000);
            }
            console.log(`✅ Cleaned up test seller group: ${testGroupName}`);
          }
        }
      } catch (e) {
        console.log(`⚠ Could not clean up test seller group: ${e}`);
      }
    }
  });

  test('Test Case 1: Navigate to seller groups management page', async ({ page }) => {
    printTestCase(1, 'Navigate to Seller Groups Management Page');
    
    const currentUrl = page.url();
    expect(currentUrl).toContain('/seller-groups-management/seller-groups');
    expect(currentUrl).not.toContain('/login');
    printSuccess('Seller groups management page accessible');
    
    const heading = page.locator('h1:has-text("Seller Groups")');
    await expect(heading).toBeVisible();
    printSuccess('Seller Groups heading visible');
    
    // Verify table is present
    const sellerGroupsTable = page.locator('#sellerGroupsTable');
    await expect(sellerGroupsTable).toBeVisible();
    printSuccess('Seller groups table visible');
    
    const createBtn = page.locator('a:has-text("Create"), button:has-text("Create")');
    await expect(createBtn.first()).toBeVisible();
    printSuccess('Create button visible');
  });

  test('Test Case 2: Test seller groups table structure', async ({ page }) => {
    printTestCase(2, 'Test Seller Groups Table Structure');
    
    await page.goto('/seller-groups-management/seller-groups');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellerGroupsTable', 15000);
    
    const sellerGroupsTable = page.locator('#sellerGroupsTable');
    
    // Verify table headers
    const headers = await sellerGroupsTable.locator('thead th').allTextContents();
    console.log(`✓ Table headers: ${headers.join(', ')}`);
    
    const expectedColumns = ['name', 'shortcode', 'status', 'companies', 'sellers', 'action'];
    let foundCount = 0;
    for (const col of expectedColumns) {
      if (headers.some(h => h.toLowerCase().includes(col))) {
        foundCount++;
        console.log(`  ✓ ${col}`);
      }
    }
    
    expect(foundCount).toBeGreaterThanOrEqual(3);
    printSuccess(`Found ${foundCount} expected seller group columns`);
    
    // Count rows
    const dataRows = await sellerGroupsTable.locator('tbody tr').count();
    console.log(`✓ Seller groups table has ${dataRows} rows`);
    expect(dataRows).toBeGreaterThanOrEqual(0);
    printSuccess('Seller groups table structure verified');
  });

  test('Test Case 3: Test create seller group workflow', async ({ page }) => {
    printTestCase(3, 'Test Create Seller Group Workflow');
    
    await page.goto('/seller-groups-management/seller-groups');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellerGroupsTable', 15000);
    
    const initialGroupCount = await page.locator('#sellerGroupsTable tbody tr').count();
    console.log(`✓ Initial seller group count: ${initialGroupCount}`);
    
    // Navigate to create seller group form
    await page.goto('/seller-groups-management/seller-groups/create');
    await page.waitForLoadState('load');
    
    const currentUrl = page.url();
    expect(currentUrl).toContain('/seller-groups-management/seller-groups/create');
    printSuccess('Navigated to create seller group form');
    
    // Fill in REQUIRED seller group information
    const shortcodeInput = page.locator('#shortcode');
    const nameInput = page.locator('#name');
    const companySelect = page.locator('#company_id');
    const vatInput = page.locator('#vat_percentage');
    const currencySelect = page.locator('#currency');
    
    await shortcodeInput.fill(testGroupShortcode);
    printSuccess(`Entered seller group shortcode: ${testGroupShortcode}`);
    
    await nameInput.fill(testGroupName);
    printSuccess(`Entered seller group name: ${testGroupName}`);
    
    // Select first seller from dropdown
    await companySelect.selectOption({ index: 1 }); // Index 0 is "Select Seller", so use index 1
    printSuccess('Selected seller from dropdown');
    
    // Fill in VAT percentage (required)
    await vatInput.fill('15');
    printSuccess('Entered VAT percentage: 15%');
    
    // Select currency (required) - Use ZAR (South African Rand) which is a valid 3-letter ISO code
    await currencySelect.selectOption('ZAR');
    printSuccess('Selected currency: ZAR');
    
    // Submit form
    const submitButton = page.locator('button[type="submit"]:has-text("Create"), button:has-text("Create Seller Group")').first();
    await submitButton.click();
    printSuccess('Submitted seller group creation form');
    
    // Wait for either success alert or error message
    await page.waitForTimeout(2000); // Give time for alert to appear
    const alertShown = await page.locator('.swal2-popup, .alert, .alert-success, .alert-danger').first().isVisible({ timeout: 2000 }).catch(() => false);
    if (alertShown) {
      const alertText = await page.locator('.swal2-popup, .alert, .alert-success, .alert-danger').first().textContent();
      console.log(`  Alert message: ${alertText}`);
      
      // Check if it's an error and fail with a clear message
      if (alertText && (alertText.includes('Error') || alertText.includes('error') || alertText.includes('failed'))) {
        throw new Error(`Backend error during seller group creation: ${alertText}. This is a backend issue that needs to be fixed.`);
      }
    }
    
    // Wait for redirect to complete - check if we're already there or wait
    const redirectUrl = page.url();
    if (!redirectUrl.includes('/seller-groups-management/seller-groups')) {
      await page.waitForURL('**/seller-groups-management/seller-groups', { timeout: 10000 }).catch(async () => {
        // If redirect didn't happen, manually navigate
        console.log('  ⚠ Auto-redirect failed, navigating manually');
        await page.goto('/seller-groups-management/seller-groups');
      });
    }
    await page.waitForLoadState('load');
    
    // Should be redirected back to seller groups list
    await waitForDataTable(page, '#sellerGroupsTable', 15000);
    
    // Look for the new seller group in the table
    const testGroupRow = page.locator(`#sellerGroupsTable tbody tr:has-text("${testGroupName}")`);
    expect(await testGroupRow.count()).toBeGreaterThan(0);
    printSuccess(`Test seller group "${testGroupName}" created successfully`);
    createdGroupId = testGroupName; // Mark for cleanup
  });

  test('Test Case 4: Test shortcode validation', async ({ page }) => {
    printTestCase(4, 'Test Shortcode Validation');
    
    await page.goto('/seller-groups-management/seller-groups/create');
    await page.waitForLoadState('load');
    
    const shortcodeInput = page.locator('#inputShortcode, #inputGroupShortcode, input[name="shortcode"]').first();
    
    if (await shortcodeInput.count() > 0) {
      // Test invalid shortcode (too short)
      await shortcodeInput.fill('AB');
      await shortcodeInput.blur();
      await page.waitForTimeout(500);
      
      // Look for validation error
      const validationError = page.locator('.invalid-feedback, .error-message, .alert-danger');
      if (await validationError.count() > 0) {
        const errorText = await validationError.first().textContent();
        console.log(`✓ Shortcode validation error: ${errorText}`);
        printSuccess('Shortcode validation working');
      } else {
        printWarning('Shortcode validation error not found');
      }
      
      // Test valid shortcode
      await shortcodeInput.fill('VALID123');
      await shortcodeInput.blur();
      await page.waitForTimeout(500);
      
      // Check if validation error is cleared
      const errorStillVisible = await validationError.count() > 0;
      if (!errorStillVisible) {
        printSuccess('Shortcode validation error cleared for valid input');
      }
    } else {
      printWarning('Shortcode input field not found');
    }
  });

  test('Test Case 5: Test seller group search functionality', async ({ page }) => {
    printTestCase(5, 'Test Seller Group Search Functionality');
    
    await page.goto('/seller-groups-management/seller-groups');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellerGroupsTable', 15000);
    
    const initialCount = await page.locator('#sellerGroupsTable tbody tr:visible').count();
    console.log(`✓ Initial seller group count: ${initialCount}`);
    
    if (initialCount === 0) {
      printWarning('No seller groups to search');
      return;
    }
    
    // Get first seller group's name
    const firstRow = page.locator('#sellerGroupsTable tbody tr:visible').first();
    const firstName = await firstRow.locator('td').first().textContent();
    console.log(`✓ First seller group: ${firstName}`);
    
    // Find search input (custom search input, not DataTables default)
    const searchInput = page.locator('#searchSellerGroups');
    
    if (await searchInput.count() === 0) {
      printWarning('Search input not found');
      return;
    }
    
    // Search for first 3 characters
    const searchTerm = firstName?.substring(0, 3) || 'test';
    await searchInput.fill(searchTerm);
    printSuccess(`Searching for: ${searchTerm}`);
    
    // Wait for DataTable to process the search (it triggers on keyup with debounce)
    await page.keyboard.press('Enter');
    await page.waitForFunction(() => {
      const table = document.querySelector('#sellerGroupsTable');
      return table && !table.classList.contains('processing');
    }, { timeout: 5000 }).catch(() => {});
    
    const filteredCount = await page.locator('#sellerGroupsTable tbody tr:visible').count();
    console.log(`✓ Filtered count: ${filteredCount}`);
    
    // Verify filtering worked
    expect(filteredCount).toBeLessThanOrEqual(initialCount);
    printSuccess('Search filtering works');
    
    // Clear search
    await searchInput.clear();
    await page.keyboard.press('Enter');
    await page.waitForFunction(() => {
      const table = document.querySelector('#sellerGroupsTable');
      return table && !table.classList.contains('processing');
    }, { timeout: 5000 }).catch(() => {});
    printSuccess('Search cleared');
  });

  test('Test Case 6: Test seller group status management', async ({ page }) => {
    printTestCase(6, 'Test Seller Group Status Management');
    
    await page.goto('/seller-groups-management/seller-groups');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellerGroupsTable', 15000);
    
    const groupRows = await page.locator('#sellerGroupsTable tbody tr').count();
    
    if (groupRows === 0) {
      printWarning('No seller groups available - skipping status test');
      return;
    }
    
    // Get first seller group
    const firstRow = page.locator('#sellerGroupsTable tbody tr').first();
    const groupName = await firstRow.locator('td').first().textContent();
    
    // Look for status toggle or status column
    const statusToggle = firstRow.locator('button:has-text("Activate"), button:has-text("Deactivate"), .status-toggle');
    const statusColumn = firstRow.locator('td:has-text("Active"), td:has-text("Inactive"), td:has-text("Enabled"), td:has-text("Disabled")');
    
    if (await statusToggle.count() > 0) {
      const initialText = await statusToggle.textContent();
      console.log(`✓ Initial status: ${initialText}`);
      
      // Toggle status
      await statusToggle.click();
      printSuccess('Clicked status toggle');
      await page.waitForTimeout(1000);
      
      const newText = await statusToggle.textContent();
      console.log(`✓ New status: ${newText}`);
      expect(newText).not.toBe(initialText);
      printSuccess('Status toggle works');
      
      // Toggle back
      await statusToggle.click();
      await page.waitForTimeout(1000);
      printSuccess('Status restored');
    } else if (await statusColumn.count() > 0) {
      const statusText = await statusColumn.textContent();
      console.log(`✓ Seller group status: ${statusText}`);
      printSuccess('Status information displayed');
    } else {
      printWarning('No status management controls found');
    }
  });

  test('Test Case 7: Test seller group company management', async ({ page }) => {
    printTestCase(7, 'Test Seller Group Company Management');
    
    await page.goto('/seller-groups-management/seller-groups');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellerGroupsTable', 15000);
    
    const groupRows = await page.locator('#sellerGroupsTable tbody tr').count();
    
    if (groupRows === 0) {
      printWarning('No seller groups available - skipping company management test');
      return;
    }
    
    // Get first seller group
    const firstRow = page.locator('#sellerGroupsTable tbody tr').first();
    const groupName = await firstRow.locator('td').first().textContent();
    
    // Look for company management button or column
    const companyButton = firstRow.locator('button:has-text("Companies"), button:has-text("Manage Companies")');
    const companyColumn = firstRow.locator('td:has-text("Company")');
    
    if (await companyButton.count() > 0) {
      await companyButton.click();
      printSuccess('Clicked company management button');
      await page.waitForTimeout(500);
      
      // Look for company management modal
      const companyModal = page.locator('.modal:has-text("Company"), .modal:has-text("Companies")');
      if (await companyModal.count() > 0) {
        printSuccess('Company management modal opened');
        
        // Look for available companies
        const companyList = companyModal.locator('.company-list, .available-companies, tr:has-text("company")');
        if (await companyList.count() > 0) {
          const companyCount = await companyList.count();
          console.log(`✓ Found ${companyCount} available companies`);
          printSuccess('Available companies displayed');
        }
        
        // Close modal
        const closeBtn = companyModal.locator('button:has-text("Close"), button.btn-close');
        await closeBtn.click();
        await page.waitForTimeout(500);
        printSuccess('Company management modal closed');
      }
    } else if (await companyColumn.count() > 0) {
      const companyText = await companyColumn.textContent();
      console.log(`✓ Seller group companies: ${companyText}`);
      printSuccess('Company information displayed');
    } else {
      printWarning('No company management controls found');
    }
  });

  test('Test Case 8: Test seller group details view', async ({ page }) => {
    printTestCase(8, 'Test Seller Group Details View');
    
    // Details view is accessed by clicking the row
    await page.goto('/seller-groups-management/seller-groups');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellerGroupsTable', 15000);
    
    const groupRows = await page.locator('#sellerGroupsTable tbody tr').count();
    expect(groupRows).toBeGreaterThan(0);
    printSuccess(`Found ${groupRows} seller groups`);
    
    // Wait for DataTable to be fully initialized and row click handlers to be attached
    await page.waitForFunction(() => {
      const tbody = document.querySelector('#sellerGroupsTable tbody');
      if (!tbody) return false;
      const events = (window as any).jQuery._data(tbody, 'events');
      return events && events.click;
    }, { timeout: 10000 });
    
    // Get first seller group row and click on it
    const firstRow = page.locator('#sellerGroupsTable tbody tr').first();
    const groupName = await firstRow.locator('td').first().textContent();
    console.log(`✓ Clicking on seller group: ${groupName}`);
    
    // Click on the seller group name cell (first td)
    await firstRow.locator('td').first().click();
    
    // Wait for navigation to complete
    await page.waitForURL(/seller-groups\/details\/[^\/]+/, { timeout: 10000 });
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(500);
    
    // Verify we're on details page
    const currentUrl = page.url();
    expect(currentUrl).toContain('seller-groups/details');
    printSuccess('Successfully navigated to seller group details page');
  });

  test('Test Case 9: Test seller group statistics', async ({ page }) => {
    printTestCase(9, 'Test Seller Group Statistics');
    
    // Statistics are on the main dashboard/index page, not in table rows
    await page.goto('/seller-groups-management');
    await page.waitForLoadState('load');
    await page.waitForTimeout(2000); // Allow AJAX stats to load
    
    // Look for statistics cards
    const totalSellerGroups = page.locator('#totalSellerGroups, .stats-number').first();
    const activeSellerGroups = page.locator('#activeSellerGroups').first();
    
    if (await totalSellerGroups.isVisible({ timeout: 3000 }).catch(() => false)) {
      printSuccess('Statistics cards found on seller groups dashboard');
      
      // Verify statistics have loaded (not showing "-")
      const totalValue = await totalSellerGroups.textContent();
      printSuccess(`Total seller groups stat: ${totalValue}`);
    } else {
      printWarning('Statistics cards not visible - may need different navigation');
    }
  });

  test('Test Case 10: Test responsive design', async ({ page }) => {
    printTestCase(10, 'Test Responsive Design');
    
    await page.goto('/seller-groups-management/seller-groups');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellerGroupsTable', 15000);
    
    const viewports = [
      { width: 1280, height: 720, name: 'Desktop' },
      { width: 768, height: 1024, name: 'Tablet' },
      { width: 375, height: 667, name: 'Mobile' }
    ];
    
    for (const viewport of viewports) {
      await page.setViewportSize({ width: viewport.width, height: viewport.height });
      console.log(`\n📱 Testing ${viewport.name} (${viewport.width}x${viewport.height})`);
      await page.waitForTimeout(500);
      
      const sellerGroupsTable = page.locator('#sellerGroupsTable');
      await expect(sellerGroupsTable).toBeVisible();
      console.log(`  ✓ Seller groups table visible`);
      
      // Check for create button (it's a link, not a button)
      const createButton = page.locator('a:has-text("Create New Seller Group")');
      const isVisible = await createButton.isVisible().catch(() => false);
      if (isVisible) {
        console.log(`  ✓ Create button accessible`);
      } else {
        console.log(`  ⚠ Create button may be in collapsed menu on ${viewport.name}`);
      }
    }
    
    // Reset viewport
    await page.setViewportSize({ width: 1280, height: 720 });
    printSuccess('All viewports tested successfully');
  });
});
