/**
 * Seller Management Test
 * 
 * Tags: @admin @p2 @regression @ui
 * 
 * Comprehensive functional testing of seller management:
 * - Seller CRUD operations (Create, Read, Update, Delete)
 * - Seller group assignments and management
 * - Seller-buyer relationships
 * - Seller user management
 * - Industry assignments and validation
 */

import { test, expect } from '@playwright/test';
import { printTestCase, printSuccess, printWarning, waitForDataTable, ensureAuthenticated } from '../../helpers/test-helpers';

test.describe('04_Partner_Management - Seller Management', () => {
  // Use authenticated state for all tests in this suite
  test.use({ storageState: 'auth.json' });

  const testSellerName = `Test Seller ${Date.now()}`;
  const testSellerCode = `TS${Date.now()}`;
  
  let createdSellerId: string | null = null;

  test.beforeEach(async ({ page }) => {
    // Ensure we're authenticated before navigating anywhere
    await ensureAuthenticated(page);
    
    console.log('\n🚀 Navigating to seller management page...');
    await page.goto('/seller-management/sellers');
    await page.waitForLoadState('load');
    console.log('✅ Seller management page loaded');
  });

  test.afterEach(async ({ page }) => {
    // Cleanup: Delete test seller if created
    if (createdSellerId) {
      try {
        await page.goto('/seller-management/sellers');
        await page.waitForLoadState('load');
        await waitForDataTable(page, '#sellersTable', 10000);
        
        // Look for test seller and delete it
        const testSellerRow = page.locator(`#sellersTable tr:has-text("${testSellerName}")`);
        if (await testSellerRow.count() > 0) {
          const deleteBtn = testSellerRow.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: ${testSellerName}`);
          }
        }
      } catch (e) {
        console.log(`⚠ Could not clean up test seller: ${e}`);
      }
    }
  });

  test('Test Case 1: Navigate to seller management page', async ({ page }) => {
    printTestCase(1, 'Navigate to Seller Management Page');
    
    const currentUrl = page.url();
    expect(currentUrl).toContain('/seller-management/sellers');
    expect(currentUrl).not.toContain('/login');
    printSuccess('Seller management page accessible');
    
    const heading = page.locator('h1:has-text("Seller Management")');
    await expect(heading).toBeVisible();
    printSuccess('Seller Management heading visible');
    
    // Verify table is present
    const sellersTable = page.locator('#sellersTable');
    await expect(sellersTable).toBeVisible();
    printSuccess('Sellers 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 sellers table structure', async ({ page }) => {
    printTestCase(2, 'Test Sellers Table Structure');
    
    await page.goto('/seller-management/sellers');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellersTable', 15000);
    
    // Wait for AJAX data to load
    await page.waitForFunction(() => {
      const table = document.querySelector('#sellersTable');
      const rows = table?.querySelectorAll('tbody tr');
      return rows && rows.length > 0 && !rows[0].textContent?.includes('Loading');
    }, { timeout: 10000 }).catch(() => {});
    
    const sellersTable = page.locator('#sellersTable');
    
    // Verify table headers
    const headers = await sellersTable.locator('thead th').allTextContents();
    console.log(`✓ Table headers: ${headers.join(', ')}`);
    
    // Check for expected columns based on actual table structure: Seller Name, GLN Number, Status, etc.
    const expectedColumns = ['seller', 'name', 'status'];
    let foundCount = 0;
    for (const col of expectedColumns) {
      if (headers.some(h => h.toLowerCase().includes(col))) {
        foundCount++;
        console.log(`  ✓ ${col}`);
      }
    }
    
    expect(foundCount).toBeGreaterThanOrEqual(2);
    printSuccess(`Found ${foundCount} expected seller columns`);
    
    // Count rows
    const dataRows = await sellersTable.locator('tbody tr').count();
    console.log(`✓ Sellers table has ${dataRows} rows`);
    expect(dataRows).toBeGreaterThan(0);
    printSuccess('Sellers table structure verified');
  });

  test('Test Case 3: Test create seller workflow', async ({ page }) => {
    printTestCase(3, 'Test Create Seller Workflow');
    
    await page.goto('/seller-management/sellers');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellersTable', 15000);
    
    const initialSellerCount = await page.locator('#sellersTable tbody tr').count();
    console.log(`✓ Initial seller count: ${initialSellerCount}`);
    
    // Navigate to create seller form
    await page.goto('/seller-management/sellers/create');
    await page.waitForLoadState('load');
    
    const currentUrl = page.url();
    expect(currentUrl).toContain('/seller-management/sellers/create');
    printSuccess('Navigated to create seller form');
    
    // Fill in REQUIRED seller information
    const nameInput = page.locator('#inputName');
    const industrySelect = page.locator('#inputIndustry');
    const emailInput = page.locator('#inputPrimaryEmail');
    
    await nameInput.fill(testSellerName);
    printSuccess(`Entered seller name: ${testSellerName}`);
    
    // Select "Retail" industry (doesn't have conditional required fields like Liquor/Pharmaceutical)
    await industrySelect.selectOption({ label: 'Retail' });
    printSuccess('Selected Retail industry');
    
    await emailInput.fill(`seller${Date.now()}@example.com`);
    printSuccess('Entered primary email');
    
    // Submit form
    const submitButton = page.locator('button[type="submit"]:has-text("Create")');
    await submitButton.click();
    printSuccess('Submitted seller creation form');
    
    // Wait for either success alert or error message
    const alertShown = await page.waitForSelector('.swal2-popup, alert, .alert-success, .alert-danger', { state: 'visible', timeout: 5000 }).catch(() => null);
    if (alertShown) {
      const alertText = await alertShown.textContent();
      console.log(`  Alert message: ${alertText}`);
    }
    
    // Wait for redirect to complete
    await page.waitForURL('**/seller-management/sellers', { timeout: 5000 }).catch(() => {});
    await page.waitForLoadState('load');
    
    // Should be redirected back to sellers list
    await waitForDataTable(page, '#sellersTable', 15000);
    
    // Look for the new seller in the table
    const testSellerRow = page.locator(`#sellersTable tbody tr:has-text("${testSellerName}")`);
    expect(await testSellerRow.count()).toBeGreaterThan(0);
    printSuccess(`Test seller "${testSellerName}" created successfully`);
    createdSellerId = testSellerName; // Mark for cleanup
  });

  test('Test Case 4: Test seller groups view', async ({ page }) => {
    printTestCase(4, 'Test Seller Groups View');
    
    await page.goto('/seller-management/sellers');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellersTable', 15000);
    
    const sellerRows = await page.locator('#sellersTable tbody tr').count();
    expect(sellerRows).toBeGreaterThan(0);
    printSuccess(`Found ${sellerRows} sellers in the table`);
    
    // Wait for DataTable to be fully initialized and row click handlers to be attached
    await page.waitForFunction(() => {
      const tbody = document.querySelector('#sellersTable tbody');
      if (!tbody) return false;
      // Check if click event is attached to tbody
      const events = (window as any).jQuery._data(tbody, 'events');
      return events && events.click;
    }, { timeout: 10000 });
    
    // Get first row and click on seller name (first cell - safe area)
    const firstRow = page.locator('#sellersTable tbody tr').first();
    const sellerName = await firstRow.locator('td').first().textContent();
    console.log(`✓ Clicking on seller: ${sellerName}`);
    
    // Click on the seller name cell (first td) which should trigger navigation
    await firstRow.locator('td').first().click();
    
    // Wait for navigation to complete
    await page.waitForURL(/seller-management\/sellers\/details\/\d+/, { timeout: 10000 });
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(500);
    
    // Verify we're on seller details page
    const detailsHeading = page.locator('h5:has-text("Seller Details"), h4:has-text("Seller Details")');
    await expect(detailsHeading.first()).toBeVisible({ timeout: 5000 });
    printSuccess('Navigated to seller details page');
    
    // Verify Seller Groups section exists
    const sellerGroupsSection = page.locator('.seller-groups-card');
    await expect(sellerGroupsSection).toBeVisible({ timeout: 5000 });
    printSuccess('Seller Groups section found');
    
    // Verify section has title and list
    const sellerGroupsTitle = sellerGroupsSection.locator(':text("Seller Groups")');
    await expect(sellerGroupsTitle).toBeVisible();
    printSuccess('Seller Groups title visible');
    
    const sellerGroupsList = page.locator('#sellerGroupsList');
    await expect(sellerGroupsList).toBeVisible();
    printSuccess('Seller Groups list displayed');
  });

  test('Test Case 5: Test seller group to store relationships', async ({ page }) => {
    printTestCase(5, 'Test Seller Group to Store Relationships');
    
    // Navigate to seller groups
    await page.goto('/seller-groups-management/seller-groups');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellerGroupsTable', 15000);
    
    const sellerGroupRows = await page.locator('#sellerGroupsTable tbody tr').count();
    expect(sellerGroupRows).toBeGreaterThan(0);
    printSuccess(`Found ${sellerGroupRows} 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 seller group details page
    const detailsHeading = page.locator('h5:has-text("Seller Group Details"), h4:has-text("Seller Group Details")');
    await expect(detailsHeading.first()).toBeVisible({ timeout: 5000 });
    printSuccess('Navigated to seller group details page');
    
    // Verify "Linked Stores" section exists
    const linkedStoresSection = page.locator(':text("Linked Stores"), :text("Link Store"), :text("Stores")');
    await expect(linkedStoresSection.first()).toBeVisible({ timeout: 5000 });
    printSuccess('Linked Stores section found - seller group to store relationships visible');
  });

  test('Test Case 6: Test seller user management', async ({ page }) => {
    printTestCase(6, 'Test Seller User Management');
    
    await page.goto('/seller-management/sellers');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellersTable', 15000);
    
    const sellerRows = await page.locator('#sellersTable tbody tr').count();
    expect(sellerRows).toBeGreaterThan(0);
    printSuccess(`Found ${sellerRows} sellers`);
    
    // Wait for DataTable to be fully initialized and row click handlers to be attached
    await page.waitForFunction(() => {
      const tbody = document.querySelector('#sellersTable tbody');
      if (!tbody) return false;
      const events = (window as any).jQuery._data(tbody, 'events');
      return events && events.click;
    }, { timeout: 10000 });
    
    // Get first row and click on seller name
    const firstRow = page.locator('#sellersTable tbody tr').first();
    const sellerName = await firstRow.locator('td').first().textContent();
    console.log(`✓ Clicking on seller: ${sellerName}`);
    
    // Click on the seller name cell (first td)
    await firstRow.locator('td').first().click();
    
    // Wait for navigation to complete
    await page.waitForURL(/seller-management\/sellers\/details\/\d+/, { timeout: 10000 });
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(500);
    
    // Verify we're on seller details page
    const detailsHeading = page.locator('h5:has-text("Seller Details"), h4:has-text("Seller Details")');
    await expect(detailsHeading.first()).toBeVisible({ timeout: 5000 });
    printSuccess('Navigated to seller details page');
    
    // Verify Seller Users section exists
    const sellerUsersSection = page.locator('.seller-users-card');
    await expect(sellerUsersSection).toBeVisible({ timeout: 5000 });
    printSuccess('Seller Users section found');
    
    // Verify "Add User" button exists
    const addUserButton = page.locator('button:has-text("Add User")');
    await expect(addUserButton).toBeVisible({ timeout: 5000 });
    printSuccess('Add User button visible');
    
    // Verify Seller Users list section exists
    const sellerUsersList = page.locator('#sellerUsersList');
    await expect(sellerUsersList).toBeVisible();
    printSuccess('Seller Users list displayed - user management is functional');
  });

  test('Test Case 7: Test seller search functionality', async ({ page }) => {
    printTestCase(7, 'Test Seller Search Functionality');
    
    await page.goto('/seller-management/sellers');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellersTable', 15000);
    
    const initialCount = await page.locator('#sellersTable tbody tr:visible').count();
    console.log(`✓ Initial seller count: ${initialCount}`);
    
    if (initialCount === 0) {
      printWarning('No sellers to search');
      return;
    }
    
    // Get first seller's name
    const firstRow = page.locator('#sellersTable tbody tr:visible').first();
    const firstName = await firstRow.locator('td').first().textContent();
    console.log(`✓ First seller: ${firstName}`);
    
    // Find search input (custom search input, not DataTables default)
    const searchInput = page.locator('#searchSellers');
    
    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('#sellersTable');
      return table && !table.classList.contains('processing');
    }, { timeout: 5000 }).catch(() => {});
    
    const filteredCount = await page.locator('#sellersTable 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('#sellersTable');
      return table && !table.classList.contains('processing');
    }, { timeout: 5000 }).catch(() => {});
    printSuccess('Search cleared');
  });

  test('Test Case 8: Test seller status management', async ({ page }) => {
    printTestCase(8, 'Test Seller Status Management');
    
    await page.goto('/seller-management/sellers');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellersTable', 15000);
    
    const sellerRows = await page.locator('#sellersTable tbody tr').count();
    
    if (sellerRows === 0) {
      printWarning('No sellers available - skipping status test');
      return;
    }
    
    // Get first seller
    const firstRow = page.locator('#sellersTable tbody tr').first();
    const sellerName = 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 status: ${statusText}`);
      printSuccess('Status information displayed');
    } else {
      printWarning('No status management controls found');
    }
  });

  test('Test Case 9: Test responsive design', async ({ page }) => {
    printTestCase(9, 'Test Responsive Design');
    
    await page.goto('/seller-management/sellers');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#sellersTable', 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 sellersTable = page.locator('#sellersTable');
      await expect(sellersTable).toBeVisible();
      console.log(`  ✓ Sellers table visible`);
      
      // Check for create button (it's a link, not a button)
      const createButton = page.locator('a:has-text("Create New Seller")');
      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');
  });
});
