import { test, expect } from '@playwright/test';
import {
  loginAsAdmin,
  waitForDataTableReload,
  waitForPageStable
} from '../helpers/wmsinventorycore';

/**
 * WMS Inventory Core - Products CRUD Tests
 *
 * Tests the Product management functionality including:
 * - Viewing products list with DataTable
 * - Filtering products by category
 * - Searching products in DataTable
 * - Viewing product details
 */

test.describe('Products CRUD Operations', () => {
  test.beforeEach(async ({ page }) => {
    await loginAsAdmin(page);
  });

  test('should display products list with DataTable', async ({ page }) => {
    // 1. Navigate to /inventory/products
    await page.goto('/inventory/products');

    // 2. Wait for DataTable to load
    await page.waitForSelector('#products-table', { timeout: 10000 });
    await waitForDataTableReload(page, '#products-table');

    // 3. Verify "All Products" heading is visible
    await expect(page.locator('h5:has-text("All Products")')).toBeVisible();

    // 4. Verify "Add New Product" button is visible
    const addButton = page.locator('a[href*="/inventory/products/create"]');
    await expect(addButton).toBeVisible();

    // 5. Verify DataTable displays columns
    await expect(page.locator('#products-table thead th:has-text("ID")')).toBeVisible();
    await expect(page.locator('#products-table thead th:has-text("Image")')).toBeVisible();
    await expect(page.locator('#products-table thead th:has-text("Name")')).toBeVisible();
    await expect(page.locator('#products-table thead th:has-text("SKU")')).toBeVisible();
    await expect(page.locator('#products-table thead th:has-text("Category")')).toBeVisible();
    await expect(page.locator('#products-table thead th:has-text("Stock")')).toBeVisible();
    // Actions column may be hidden on smaller screens due to responsive design

    // 6. Verify at least one product row exists or empty message
    await page.waitForTimeout(1000);
    const rowCount = await page.locator('#products-table tbody tr').count();
    expect(rowCount).toBeGreaterThan(0);

    // 7. Verify pagination controls are visible
    await expect(page.locator('.dataTables_paginate')).toBeVisible();
  });

  test('should filter products by category', async ({ page }) => {
    // 1. Navigate to /inventory/products
    await page.goto('/inventory/products');

    // 2. Wait for DataTable to load
    await page.waitForSelector('#products-table', { timeout: 10000 });
    await waitForDataTableReload(page, '#products-table');
    await page.waitForTimeout(1000);

    // 3. Verify category filter exists
    const categoryFilter = page.locator('#category-filter');
    await expect(categoryFilter).toBeVisible();

    // Check if there are options to select
    const optionCount = await categoryFilter.locator('option').count();
    if (optionCount <= 1) {
      test.skip();
      return;
    }

    // 4. Select a specific category
    await categoryFilter.selectOption({ index: 1 });

    // 5. Wait for DataTable to refresh
    await page.waitForTimeout(1000);
    await waitForDataTableReload(page, '#products-table');

    // 6. Verify DataTable is still visible
    await expect(page.locator('#products-table')).toBeVisible();

    // 7. Select "All Categories" to reset
    await categoryFilter.selectOption('');

    // 8. Verify all products return
    await page.waitForTimeout(1000);
    await waitForDataTableReload(page, '#products-table');
    await expect(page.locator('#products-table')).toBeVisible();
  });

  test('should search products in DataTable', async ({ page }) => {
    // 1. Navigate to /inventory/products
    await page.goto('/inventory/products');

    // 2. Wait for DataTable to load
    await page.waitForSelector('#products-table', { timeout: 10000 });
    await waitForDataTableReload(page, '#products-table');
    await page.waitForTimeout(1000);

    // Check for data in table
    const rowCount = await page.locator('#products-table tbody tr').count();
    const emptyTableRow = await page.locator('#products-table tbody tr td.dataTables_empty').count();

    if (rowCount === 0 || emptyTableRow > 0) {
      test.skip();
      return;
    }

    // 3. Type search term in search box
    const searchBox = page.locator('#products-table_filter input[type="search"], .dataTables_filter input');
    await searchBox.fill('Product');

    // 4. Wait for DataTable to refresh
    await page.waitForTimeout(1000);

    // 5. Verify DataTable shows results
    await expect(page.locator('#products-table')).toBeVisible();

    // 6. Clear search box
    await searchBox.clear();

    // 7. Verify all products return
    await page.waitForTimeout(1000);
    await expect(page.locator('#products-table')).toBeVisible();
  });

  test('should view product details', async ({ page }) => {
    // Set larger viewport for DataTable responsive columns
    await page.setViewportSize({ width: 1920, height: 1080 });

    // 1. Navigate to /inventory/products
    await page.goto('/inventory/products');

    await page.waitForSelector('#products-table', { timeout: 10000 });
    await waitForDataTableReload(page, '#products-table');
    await page.waitForTimeout(1000);

    // Wait for at least one row
    const rowCount = await page.locator('#products-table tbody tr').count();
    const emptyTableRow = await page.locator('#products-table tbody tr td.dataTables_empty').count();

    if (rowCount === 0 || emptyTableRow > 0) {
      test.skip();
      return;
    }

    // 2. Click action button on first product row
    const firstRow = page.locator('#products-table tbody tr').first();
    const dropdownToggle = firstRow.locator('a.dropdown-toggle, .dropdown-toggle').first();
    await dropdownToggle.click({ force: true });
    await page.waitForTimeout(300);

    // 3. Click "View" option
    const viewButton = page.locator('.dropdown-item:has-text("View")').first();
    await viewButton.click();

    // 4. Verify redirect to product detail page
    await page.waitForURL(/\/inventory\/products\/\d+$/, { timeout: 10000 });
    await waitForPageStable(page);
    await page.waitForTimeout(1000);

    // 5. Verify product information displays - page should load successfully
    const pageContent = page.locator('body');
    await expect(pageContent).toBeVisible();

    // Check for product details - either in card or page content
    const hasProductInfo = await page.locator('text=SKU').count() > 0 ||
                           await page.locator('text=Product').count() > 0;
    expect(hasProductInfo).toBeTruthy();

    // 6. Verify Edit button is visible (if user has permission)
    const editButton = page.locator('a[href*="/edit"]').first();
    if (await editButton.count() > 0) {
      await expect(editButton).toBeVisible();
    }

    // 7. Page loaded successfully - test complete
  });
});
