import { test, expect } from '@playwright/test';
import {
  loginAsAdmin,
  generateUniqueCode,
  generateUniqueName,
  navigateToProducts,
  navigateToProductCreate,
  confirmSweetAlert,
  waitForPageStable,
  waitForDataTableReload
} from '../helpers/systemcore';

/**
 * Products CRUD Tests
 *
 * Tests the Product management functionality including:
 * - Viewing products list page
 * - Creating a product with required fields
 * - Creating a product with all fields
 * - Validation errors for required fields
 * - Viewing product details
 * - Editing an existing product
 * - Deleting a product with confirmation
 */

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

  test('should display products list page', async ({ page }) => {
    // Navigate to /systemcore/products
    await navigateToProducts(page);

    // Verify DataTable is visible
    await expect(page.locator('#productsTable')).toBeVisible();

    // Verify page has card wrapper (use .first() since there may be multiple cards)
    await expect(page.locator('.card').first()).toBeVisible();

    // Verify Add Product button exists
    const addButton = page.locator('a[href*="/systemcore/products/create"]');
    await expect(addButton).toBeVisible();
  });

  test('should navigate to create product page', async ({ page }) => {
    // Navigate to products list
    await navigateToProducts(page);

    // Click "Add Product" button
    await page.click('a[href*="/systemcore/products/create"]');

    // Verify form page loads
    await page.waitForURL('**/systemcore/products/create', { timeout: 10000 });
    await waitForPageStable(page);

    // Verify form is visible
    await expect(page.locator('#productForm')).toBeVisible();

    // Verify required form fields are present
    await expect(page.locator('#name')).toBeVisible();
    await expect(page.locator('#sku')).toBeVisible();
  });

  test('should create product with required fields', async ({ page }) => {
    // Navigate to create page
    await navigateToProductCreate(page);
    await waitForPageStable(page);

    // Fill: name
    const productName = generateUniqueName('Test Product');
    await page.locator('#name').fill(productName);

    // Fill: SKU
    const productSku = generateUniqueCode('SKU');
    await page.locator('#sku').fill(productSku);

    // Fill: base_price
    await page.locator('#base_price').fill('100.00');

    // Fill: selling_price
    await page.locator('#selling_price').fill('150.00');

    // Submit form
    await page.locator('#productForm button[type="submit"]').click();

    // Verify redirect to show or list page
    await page.waitForLoadState('networkidle');
    await page.waitForURL(/\/systemcore\/products(\/.+)?$/, { timeout: 10000 });

    // Verify we're on a valid product page
    const currentUrl = page.url();
    expect(currentUrl).toMatch(/\/systemcore\/products/);
  });

  test('should create product with all fields', async ({ page }) => {
    // Navigate to create page
    await navigateToProductCreate(page);
    await waitForPageStable(page);

    // Fill all fields
    const productName = generateUniqueName('Complete Product');
    const productSku = generateUniqueCode('SKU');

    await page.locator('#name').fill(productName);
    await page.locator('#sku').fill(productSku);
    await page.locator('#barcode').fill('BAR' + Date.now().toString().slice(-10));
    await page.locator('#brand').fill('Test Brand');
    await page.locator('#description').fill('Test product created via E2E test');

    // Select category if available
    const categorySelect = page.locator('#category_id');
    if (await categorySelect.count() > 0) {
      const options = await categorySelect.locator('option').count();
      if (options > 1) {
        await categorySelect.selectOption({ index: 1 });
      }
    }

    // Select unit of measure if available
    const uomSelect = page.locator('#unit_of_measure');
    if (await uomSelect.count() > 0) {
      await uomSelect.selectOption('pcs');
    }

    // Fill pricing
    await page.locator('#base_price').fill('100.00');
    await page.locator('#cost_price').fill('80.00');
    await page.locator('#selling_price').fill('150.00');

    // Fill stock management
    const minStock = page.locator('#min_stock_level');
    if (await minStock.count() > 0) {
      await minStock.fill('10');
    }

    const maxStock = page.locator('#max_stock_level');
    if (await maxStock.count() > 0) {
      await maxStock.fill('1000');
    }

    const reorderLevel = page.locator('#reorder_level');
    if (await reorderLevel.count() > 0) {
      await reorderLevel.fill('50');
    }

    // Submit and verify
    await page.locator('#productForm button[type="submit"]').click();

    // Wait for response
    await page.waitForLoadState('networkidle');
    await page.waitForURL(/\/systemcore\/products(\/.+)?$/, { timeout: 10000 });

    // Verify redirect
    const currentUrl = page.url();
    expect(currentUrl).toMatch(/\/systemcore\/products/);
  });

  test('should show validation error for empty required fields', async ({ page }) => {
    // Navigate to create page
    await navigateToProductCreate(page);
    await waitForPageStable(page);

    // Submit without filling required fields
    await page.locator('#productForm button[type="submit"]').click();

    // Wait a moment for validation
    await page.waitForTimeout(500);

    // Form should still be visible
    await expect(page.locator('#productForm')).toBeVisible();

    // Check that we're still on the create page
    const currentUrl = page.url();
    expect(currentUrl).toContain('/create');
  });

  test('should view product details', async ({ page }) => {
    // Navigate to products list
    await navigateToProducts(page);
    await waitForPageStable(page);

    // Wait for DataTable to load
    await waitForDataTableReload(page, '#productsTable');
    await page.waitForTimeout(1000);

    // Wait for at least one row
    await page.waitForSelector('#productsTable tbody tr', { timeout: 10000 });

    // Get the first row
    const firstRow = page.locator('#productsTable tbody tr').first();

    // Click the dropdown toggle to open the actions menu
    const dropdownToggle = firstRow.locator('.btn-icon.dropdown-toggle, button.dropdown-toggle').first();
    const dropdownCount = await dropdownToggle.count();

    if (dropdownCount === 0) {
      test.skip();
      return;
    }

    await dropdownToggle.click();
    await page.waitForTimeout(300);

    // Click the view button from the dropdown menu
    const viewButton = page.locator('.dropdown-item:has-text("View"), a.dropdown-item[href*="/systemcore/products/"]:not([href*="/edit"])').first();
    const viewButtonCount = await viewButton.count();

    if (viewButtonCount === 0) {
      test.skip();
      return;
    }

    await viewButton.click();

    // Verify show page displays product info
    await page.waitForURL(/\/systemcore\/products\/\d+$/, { timeout: 10000 });
    await waitForPageStable(page);

    // Verify product information is displayed
    await expect(page.locator('.card').first()).toBeVisible();
  });

  test('should edit existing product', async ({ page }) => {
    // Navigate to products list
    await navigateToProducts(page);
    await waitForPageStable(page);

    // Wait for DataTable to load
    await waitForDataTableReload(page, '#productsTable');
    await page.waitForTimeout(1000);

    // Wait for at least one row
    await page.waitForSelector('#productsTable tbody tr', { timeout: 10000 });

    // Get the first row
    const firstRow = page.locator('#productsTable tbody tr').first();

    // Click the dropdown toggle to open the actions menu
    const dropdownToggle = firstRow.locator('.btn-icon.dropdown-toggle, button.dropdown-toggle').first();
    const dropdownCount = await dropdownToggle.count();

    if (dropdownCount === 0) {
      test.skip();
      return;
    }

    await dropdownToggle.click();
    await page.waitForTimeout(300);

    // Click the edit button from the dropdown menu
    const editButton = page.locator('.dropdown-item:has-text("Edit"), a.dropdown-item[href*="/edit"]').first();
    const editButtonCount = await editButton.count();

    if (editButtonCount === 0) {
      test.skip();
      return;
    }

    await editButton.click();

    // Wait for edit page
    await page.waitForURL('**/edit', { timeout: 10000 });
    await waitForPageStable(page);

    // Verify we're on edit page
    await expect(page.locator('#productForm')).toBeVisible();

    // Modify fields
    const updatedName = generateUniqueName('Updated Product');
    await page.locator('#name').fill(updatedName);

    // Save and verify changes
    await page.locator('#productForm button[type="submit"]').click();

    // Wait for response
    await page.waitForLoadState('networkidle');

    // Verify redirect
    await page.waitForTimeout(1000);
    const currentUrl = page.url();
    expect(currentUrl).toMatch(/\/systemcore\/products/);
  });

  test('should delete product with confirmation', async ({ page }) => {
    // Navigate to products list
    await navigateToProducts(page);
    await waitForPageStable(page);

    // Wait for DataTable to load
    await waitForDataTableReload(page, '#productsTable');
    await page.waitForTimeout(1000);

    // Wait for at least one row
    await page.waitForSelector('#productsTable tbody tr', { timeout: 10000 });

    // Count initial rows
    const initialRowCount = await page.locator('#productsTable tbody tr').count();

    if (initialRowCount === 0) {
      test.skip();
      return;
    }

    // Get the first row
    const firstRow = page.locator('#productsTable tbody tr').first();

    // Click the dropdown toggle to open the actions menu
    const dropdownToggle = firstRow.locator('.btn-icon.dropdown-toggle, button.dropdown-toggle').first();
    const dropdownCount = await dropdownToggle.count();

    if (dropdownCount === 0) {
      test.skip();
      return;
    }

    await dropdownToggle.click();
    await page.waitForTimeout(300);

    // Find and click delete button from the dropdown menu
    const deleteButton = page.locator('.dropdown-item.text-danger:has-text("Delete"), .dropdown-item[onclick*="delete"]').first();

    if (await deleteButton.count() === 0) {
      test.skip();
      return;
    }

    await deleteButton.click();

    // Confirm SweetAlert dialog
    await confirmSweetAlert(page);

    // Wait for deletion
    await page.waitForTimeout(1000);

    // Verify table is still visible
    await waitForDataTableReload(page, '#productsTable');
    await expect(page.locator('#productsTable')).toBeVisible();
  });

  test('should cancel creation and return to list', async ({ page }) => {
    // Navigate to create page
    await navigateToProductCreate(page);
    await waitForPageStable(page);

    // Fill some data
    await page.locator('#name').fill('Will be cancelled');
    await page.locator('#sku').fill(generateUniqueCode('SKU'));

    // Click cancel button
    const cancelButton = page.locator('a:has-text("Cancel"), a.btn-label-secondary').first();
    await cancelButton.click();

    // Should navigate back to list
    await page.waitForURL('**/systemcore/products', { timeout: 10000 });
    await waitForPageStable(page);

    await expect(page.locator('#productsTable')).toBeVisible();
  });
});
