/**
 * Industry Management Test
 * 
 * Tags: @admin @p2 @regression @ui
 * 
 * Comprehensive functional testing of industry management:
 * - Industry CRUD operations (Create, Read, Update, Delete)
 * - Industry status management and toggling
 * - Data validation and error handling
 * - Export functionality
 * - Search and filtering capabilities
 */

import { test, expect } from '@playwright/test';
import { printTestCase, printSuccess, printWarning, waitForDataTable, ensureAuthenticated } from '../../helpers/test-helpers';

test.describe('04_Partner_Management - Industry Management', () => {
  // Use authenticated state for all tests in this suite
  test.use({ storageState: 'auth.json' });

  const testIndustryName = `Test Industry ${Date.now()}`;
  const testIndustryDescription = `Test industry description for ${Date.now()}`;
  
  let createdIndustryId: string | null = null;

  test.beforeEach(async ({ page }) => {
    // Ensure we're authenticated before navigating anywhere
    await ensureAuthenticated(page);
    
    console.log('\n🚀 Navigating to industry management page...');
    await page.goto('/industrymanagement/industries');
    await page.waitForLoadState('load');
    console.log('✅ Industry management page loaded');
  });

  test.afterEach(async ({ page }) => {
    // Cleanup: Delete test industry if created
    if (createdIndustryId) {
      try {
        await page.goto('/industrymanagement/industries');
        await page.waitForLoadState('load');
        await waitForDataTable(page, 'table', 10000);
        
        // Look for test industry and delete it
        const testIndustryRow = page.locator(`table tr:has-text("${testIndustryName}")`);
        if (await testIndustryRow.count() > 0) {
          const deleteBtn = testIndustryRow.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 industry: ${testIndustryName}`);
          }
        }
      } catch (e) {
        console.log(`⚠ Could not clean up test industry: ${e}`);
      }
    }
  });

  test('Test Case 1: Navigate to industry management page', async ({ page }) => {
    printTestCase(1, 'Navigate to Industry Management Page');
    
    const currentUrl = page.url();
    expect(currentUrl).toContain('/industrymanagement/industries');
    expect(currentUrl).not.toContain('/login');
    printSuccess('Industry management page accessible');
    
    const heading = page.locator('h1:has-text("Industry Management")');
    await expect(heading).toBeVisible();
    printSuccess('Industry Management heading visible');
    
    // Verify industries table is present
    const industriesTable = page.locator('table').first();
    if (await industriesTable.count() > 0) {
      await expect(industriesTable).toBeVisible();
      printSuccess('Industries table visible');
    } else {
      printWarning('Industries table not found - may be using different layout');
    }
    
    // Test create button
    const createBtn = page.locator('a:has-text("Create New Industry")');
    if (await createBtn.count() > 0) {
      await expect(createBtn).toBeVisible();
      printSuccess('Create New Industry button visible');
    }
  });

  test('Test Case 2: Test industries table structure', async ({ page }) => {
    printTestCase(2, 'Test Industries Table Structure');
    
    await page.goto('/industrymanagement/industries');
    await page.waitForLoadState('load');
    
    try {
      await waitForDataTable(page, 'table', 15000);
    } catch (e) {
      console.log('⚠ Waiting for table with alternative approach');
      await page.waitForTimeout(3000);
    }
    
    const industriesTable = page.locator('table, table').first();
    
    if (await industriesTable.count() > 0) {
      // Verify table headers
      const headers = await industriesTable.locator('thead th, th').allTextContents();
      console.log(`✓ Table headers: ${headers.join(', ')}`);
      
      const expectedColumns = ['name', 'description', 'status', 'updated_by', 'updated_at', '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 industry columns`);
      
      // Count rows
      const dataRows = await industriesTable.locator('tbody tr, tr').count();
      console.log(`✓ Industries table has ${dataRows} rows`);
      expect(dataRows).toBeGreaterThanOrEqual(0);
      printSuccess('Industries table structure verified');
    } else {
      printWarning('Industries table not found - may be using different layout');
    }
  });

  test('Test Case 3: Test create industry workflow', async ({ page }) => {
    printTestCase(3, 'Test Create Industry Workflow');
    
    await page.goto('/industrymanagement/industries');
    await page.waitForLoadState('load');
    
    try {
      await waitForDataTable(page, 'table', 15000);
    } catch (e) {
      await page.waitForTimeout(3000);
    }
    
    const industriesTable = page.locator('table, table').first();
    const initialIndustryCount = await industriesTable.locator('tbody tr, tr').count();
    console.log(`✓ Initial industry count: ${initialIndustryCount}`);
    
    // Navigate to create industry form
    await page.goto('/industrymanagement/industries/create');
    await page.waitForLoadState('load');
    
    const currentUrl = page.url();
    expect(currentUrl).toContain('/industrymanagement/industries/create');
    printSuccess('Navigated to create industry form');
    
    // Fill in industry information
    const nameInput = page.locator('#inputName, #inputIndustryName, input[name="name"]').first();
    const descriptionInput = page.locator('#inputDescription, #inputIndustryDescription, textarea[name="description"]').first();
    
    if (await nameInput.count() > 0) {
      await nameInput.fill(testIndustryName);
      printSuccess(`Entered industry name: ${testIndustryName}`);
    }
    
    if (await descriptionInput.count() > 0) {
      await descriptionInput.fill(testIndustryDescription);
      printSuccess(`Entered industry description: ${testIndustryDescription}`);
    }
    
    // Check active status if available
    const activeCheckbox = page.locator('#inputActive, input[name="active"], input[type="checkbox"]').first();
    if (await activeCheckbox.count() > 0) {
      await activeCheckbox.check();
      printSuccess('Checked active status');
    }
    
    // Submit form
    const submitButton = page.locator('button[type="submit"], button:has-text("Save"), button:has-text("Create")').first();
    if (await submitButton.count() > 0) {
      await submitButton.click();
      printSuccess('Submitted industry creation form');
      
      // Wait for redirect
      await page.waitForTimeout(2000);
      await page.waitForLoadState('load');
      
      // Navigate back to industries list to verify creation
      await page.goto('/industrymanagement/industries');
      await page.waitForLoadState('load');
      
      try {
        await waitForDataTable(page, 'table', 15000);
      } catch (e) {
        await page.waitForTimeout(3000);
      }
      
      // Look for the new industry in the table
      const testIndustryRow = page.locator(`table tr:has-text("${testIndustryName}"), .industries-table tr:has-text("${testIndustryName}")`);
      expect(await testIndustryRow.count()).toBeGreaterThan(0);
      printSuccess(`Test industry "${testIndustryName}" created successfully`);
      createdIndustryId = testIndustryName; // Mark for cleanup
    }
  });

  test('Test Case 4: Test industry validation', async ({ page }) => {
    printTestCase(4, 'Test Industry Validation');
    
    await page.goto('/industrymanagement/industries/create');
    await page.waitForLoadState('load');
    
    const nameInput = page.locator('#inputName');
    await expect(nameInput).toBeVisible({ timeout: 5000 });
    
    // Submit with empty name to trigger validation
    const submitButton = page.locator('button[type="submit"]:has-text("Create")');
    await submitButton.click();
    
    // Wait for AJAX response
    await page.waitForTimeout(1000);
    
    // Look for validation error (server-side validation via AJAX shows in .invalid-feedback)
    const validationError = page.locator('.invalid-feedback:visible, .error-message:visible, .alert-danger:visible, .text-danger:visible');
    await expect(validationError).toBeVisible({ timeout: 3000 });
    printSuccess('Industry validation works correctly');
  });

  test('Test Case 5: Test industry search functionality', async ({ page }) => {
    printTestCase(5, 'Test Industry Search Functionality');
    
    await page.goto('/industrymanagement/industries');
    await page.waitForLoadState('load');
    
    await waitForDataTable(page, '#industriesTable', 15000);
    
    const industriesTable = page.locator('#industriesTable');
    const initialCount = await industriesTable.locator('tbody tr').count();
    console.log(`✓ Initial industry count: ${initialCount}`);
    
    if (initialCount === 0) {
      printWarning('No industries to search');
      return;
    }
    
    // Get first industry's name
    const firstRow = industriesTable.locator('tbody tr').first();
    const firstName = await firstRow.locator('td').first().textContent();
    console.log(`✓ First industry: ${firstName}`);
    
    // Find search input (custom search input, not DataTables default)
    const searchInput = page.locator('#searchIndustries');
    
    if (await searchInput.count() > 0) {
      // 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)
      await page.keyboard.press('Enter');
      await page.waitForFunction(() => {
        const table = document.querySelector('#industriesTable');
        return table && !table.classList.contains('processing');
      }, { timeout: 5000 }).catch(() => {});
      
      const filteredCount = await industriesTable.locator('tbody tr').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('#industriesTable');
        return table && !table.classList.contains('processing');
      }, { timeout: 5000 }).catch(() => {});
      printSuccess('Search cleared');
    } else {
      printWarning('Search input not found');
    }
  });

  test('Test Case 6: Test industry status management', async ({ page }) => {
    printTestCase(6, 'Test Industry Status Management');
    
    await page.goto('/industrymanagement/industries');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#industriesTable', 15000);
    
    // Wait for AJAX data to load
    await page.waitForFunction(() => {
      const table = document.querySelector('#industriesTable');
      const rows = table?.querySelectorAll('tbody tr');
      return rows && rows.length > 0 && !rows[0].textContent?.includes('Loading');
    }, { timeout: 10000 }).catch(() => {});
    
    const industriesTable = page.locator('#industriesTable');
    const industryRows = await industriesTable.locator('tbody tr').count();
    
    if (industryRows === 0) {
      printWarning('No industries available - skipping status test');
      return;
    }
    
    // Get first industry
    const firstRow = industriesTable.locator('tbody tr').first();
    const industryName = 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(`✓ Industry status: ${statusText}`);
      printSuccess('Status information displayed');
    } else {
      printWarning('No status management controls found');
    }
  });

  test('Test Case 7: Test industry details view', async ({ page }) => {
    printTestCase(7, 'Test Industry Details View');
    
    await page.goto('/industrymanagement/industries');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#industriesTable', 15000);
    
    // Wait for AJAX data to load
    await page.waitForFunction(() => {
      const table = document.querySelector('#industriesTable');
      const rows = table?.querySelectorAll('tbody tr');
      return rows && rows.length > 0 && !rows[0].textContent?.includes('Loading');
    }, { timeout: 10000 });
    
    const industriesTable = page.locator('#industriesTable');
    const industryRows = await industriesTable.locator('tbody tr').count();
    expect(industryRows).toBeGreaterThan(0);
    printSuccess(`Found ${industryRows} industries in the table`);
    
    // Wait for DataTable to be fully initialized and row click handlers to be attached
    await page.waitForFunction(() => {
      const tbody = document.querySelector('#industriesTable tbody');
      if (!tbody) return false;
      const events = (window as any).jQuery._data(tbody, 'events');
      return events && events.click;
    }, { timeout: 10000 });
    
    // Get first industry row and click on it
    const firstRow = industriesTable.locator('tbody tr').first();
    const industryName = await firstRow.locator('td').first().textContent();
    console.log(`✓ Clicking on industry: ${industryName}`);
    
    // Click on the industry name cell (first td)
    await firstRow.locator('td').first().click();
    
    // Wait for navigation to complete
    await page.waitForURL(/industrymanagement\/industries\/details\/\d+/, { timeout: 10000 });
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(500);
    
    // Verify we're on industry details page
    const detailsHeading = page.locator('h5:has-text("Industry Details"), h4:has-text("Industry Details")');
    await expect(detailsHeading.first()).toBeVisible({ timeout: 5000 });
    printSuccess('Successfully navigated to industry details page');
    
    // Verify industry information form is displayed
    const nameInput = page.locator('#inputName, input[name="name"]');
    await expect(nameInput).toBeVisible();
    printSuccess('Industry details form displayed');
  });

  test('Test Case 8: Test industry export functionality', async ({ page }) => {
    printTestCase(8, 'Test Industry Export Functionality');
    
    await page.goto('/industrymanagement/industries');
    await page.waitForLoadState('load');
    
    try {
      await waitForDataTable(page, 'table', 15000);
    } catch (e) {
      await page.waitForTimeout(3000);
    }
    
    // Look for export button
    const exportButton = page.locator('button:has-text("Export"), a:has-text("Export"), button:has-text("Excel")');
    
    if (await exportButton.count() > 0) {
      await expect(exportButton).toBeVisible();
      printSuccess('Export button visible');
      
      // Test export functionality
      await exportButton.click();
      printSuccess('Clicked export button');
      await page.waitForTimeout(2000);
      
      // Check if download started or modal opened
      const downloadModal = page.locator('.modal:has-text("Export"), .modal:has-text("Download")');
      if (await downloadModal.count() > 0) {
        printSuccess('Export modal opened');
        
        // Close modal
        const closeBtn = downloadModal.locator('button:has-text("Close"), button.btn-close');
        await closeBtn.click();
        await page.waitForTimeout(500);
        printSuccess('Export modal closed');
      } else {
        printSuccess('Export functionality triggered');
      }
    } else {
      printWarning('Export button not found');
    }
  });

  test('Test Case 9: Test industry edit workflow', async ({ page }) => {
    printTestCase(9, 'Test Industry Edit Workflow');
    
    await page.goto('/industrymanagement/industries');
    await page.waitForLoadState('load');
    await waitForDataTable(page, '#industriesTable', 15000);
    
    // Wait for AJAX data to load
    await page.waitForFunction(() => {
      const table = document.querySelector('#industriesTable');
      const rows = table?.querySelectorAll('tbody tr');
      return rows && rows.length > 0 && !rows[0].textContent?.includes('Loading');
    }, { timeout: 10000 });
    
    const industriesTable = page.locator('#industriesTable');
    const industryRows = await industriesTable.locator('tbody tr').count();
    expect(industryRows).toBeGreaterThan(0);
    printSuccess(`Found ${industryRows} industries`);
    
    // Wait for DataTable to be fully initialized and row click handlers to be attached
    await page.waitForFunction(() => {
      const tbody = document.querySelector('#industriesTable tbody');
      if (!tbody) return false;
      const events = (window as any).jQuery._data(tbody, 'events');
      return events && events.click;
    }, { timeout: 10000 });
    
    // Get first industry row and click on it
    const firstIndustryRow = industriesTable.locator('tbody tr').first();
    const originalIndustryName = await firstIndustryRow.locator('td').first().textContent();
    console.log(`✓ Clicking on industry: ${originalIndustryName}`);
    
    // Click on the industry name cell (first td)
    await firstIndustryRow.locator('td').first().click();
    
    // Wait for navigation to complete
    await page.waitForURL(/industrymanagement\/industries\/details\/\d+/, { timeout: 10000 });
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(500);
    
    // Verify we're on industry details page
    const detailsHeading = page.locator('h5:has-text("Industry Details"), h4:has-text("Industry Details")');
    await expect(detailsHeading.first()).toBeVisible({ timeout: 5000 });
    printSuccess('Navigated to industry details page');
    
    // Verify edit form fields are present on the details page
    const nameInput = page.locator('#inputName, input[name="name"]');
    await expect(nameInput).toBeVisible({ timeout: 5000 });
    printSuccess('Industry name field visible');
    
    const descriptionInput = page.locator('#inputDescription, textarea[name="description"]');
    await expect(descriptionInput.first()).toBeVisible({ timeout: 5000 });
    printSuccess('Industry edit form is accessible and functional');
  });

  test('Test Case 10: Test responsive design', async ({ page }) => {
    printTestCase(10, 'Test Responsive Design');
    
    await page.goto('/industrymanagement/industries');
    await page.waitForLoadState('load');
    
    try {
      await waitForDataTable(page, 'table', 15000);
    } catch (e) {
      await page.waitForTimeout(3000);
    }
    
    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 industriesTable = page.locator('table, table').first();
      if (await industriesTable.count() > 0) {
        await expect(industriesTable).toBeVisible();
        console.log(`  ✓ Industries table visible`);
      }
      
      const createButton = page.locator('button:has-text("Create"), button:has-text("Add")').first();
      if (await createButton.count() > 0) {
        await expect(createButton).toBeVisible();
        console.log(`  ✓ Create button accessible`);
      }
    }
    
    // Reset viewport
    await page.setViewportSize({ width: 1280, height: 720 });
    printSuccess('All viewports tested successfully');
  });
});
