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

/**
 * Product Categories CRUD Tests
 *
 * Tests the Product Categories management functionality including:
 * - Viewing product categories list
 * - Creating root categories
 * - Creating child categories with parent
 * - Editing existing categories
 * - Deleting categories with confirmation
 */

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

  test('should display product categories list page', async ({ page }) => {
    // Navigate to product categories page
    await navigateToProductCategories(page);

    // Verify page loaded with card and table visible (use .first() since there may be multiple cards)
    await expect(page.locator('.card').first()).toBeVisible();
    await expect(page.locator('#productCategoriesTable')).toBeVisible();

    // Verify Add Product Category button exists
    await expect(page.locator('a[href*="product-categories/create"]')).toBeVisible();
  });

  test('should navigate to create product category page', async ({ page }) => {
    await navigateToProductCategories(page);

    // Click "Add Product Category" button
    await page.click('a[href*="product-categories/create"]');
    await waitForPageStable(page);

    // Verify we're on the create form page
    await expect(page.locator('#productCategoryForm')).toBeVisible();
    await expect(page.locator('#name')).toBeVisible();
    await expect(page.locator('#code')).toBeVisible();
  });

  test('should create a root category', async ({ page }) => {
    await navigateToProductCategoryCreate(page);

    // Fill form fields for root category
    const categoryName = generateUniqueName('Electronics');
    const categoryCode = generateUniqueCode('CAT');

    // Fill name field
    await page.locator('#name').fill(categoryName);

    // Fill code field
    await page.locator('#code').fill(categoryCode);

    // Leave parent_id empty (root category)

    // Check is_active checkbox
    const isActiveCheckbox = page.locator('#is_active');
    if (!(await isActiveCheckbox.isChecked())) {
      await isActiveCheckbox.check();
    }

    // Fill description
    await page.locator('#description').fill('Test root category created by E2E test');

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

    // Wait for success and verify
    await waitForPageStable(page);
    await page.waitForURL('**/product-categories', { timeout: 10000 });
    await expect(page.locator('#productCategoriesTable')).toBeVisible();
  });

  test('should create a child category with parent', async ({ page }) => {
    await navigateToProductCategoryCreate(page);

    // Fill form fields for child category
    const categoryName = generateUniqueName('Smartphones');
    const categoryCode = generateUniqueCode('CAT');

    // Fill name field
    await page.locator('#name').fill(categoryName);

    // Fill code field
    await page.locator('#code').fill(categoryCode);

    // Select parent category
    const parentOptions = await page.locator('#parent_id option').count();

    if (parentOptions > 1) {
      // Select the first available parent category
      await page.selectOption('#parent_id', { index: 1 });
    }

    // Check is_active checkbox
    const isActiveCheckbox = page.locator('#is_active');
    if (!(await isActiveCheckbox.isChecked())) {
      await isActiveCheckbox.check();
    }

    // Fill description
    await page.locator('#description').fill('Test child category with parent');

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

    // Wait for success and verify
    await waitForPageStable(page);
    await page.waitForURL('**/product-categories', { timeout: 10000 });
    await expect(page.locator('#productCategoriesTable')).toBeVisible();
  });

  test('should edit existing category', async ({ page }) => {
    // Navigate to the list page
    await navigateToProductCategories(page);
    await waitForPageStable(page);

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

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

    // Get the first row
    const firstRow = page.locator('#productCategoriesTable 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 the edit form
    await expect(page.locator('#productCategoryForm')).toBeVisible();

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

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

    // Wait for success and verify redirect
    await waitForPageStable(page);
    await page.waitForURL('**/product-categories', { timeout: 10000 });
    await expect(page.locator('#productCategoriesTable')).toBeVisible();
  });

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

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

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

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

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

    // Get the first row
    const firstRow = page.locator('#productCategoriesTable 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, '#productCategoriesTable');
    await expect(page.locator('#productCategoriesTable')).toBeVisible();
  });

  test('should show validation error for empty name', async ({ page }) => {
    await navigateToProductCategoryCreate(page);

    // Fill only code, leave name empty
    await page.locator('#code').fill(generateUniqueCode('CAT'));

    // Try to submit
    await page.click('button[type="submit"]');

    // Should stay on the same page
    await page.waitForTimeout(500);

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

  test('should cancel form and return to list', async ({ page }) => {
    await navigateToProductCategoryCreate(page);

    // Fill some data
    await page.locator('#name').fill('Test Category');
    await page.locator('#code').fill(generateUniqueCode('CAT'));

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

    // Should return to list page
    await waitForPageStable(page);
    await expect(page.locator('#productCategoriesTable')).toBeVisible();
  });

  test('should toggle active status checkbox', async ({ page }) => {
    await navigateToProductCategoryCreate(page);

    const isActiveCheckbox = page.locator('#is_active');

    // Check current state
    const isChecked = await isActiveCheckbox.isChecked();

    // Toggle the checkbox
    if (isChecked) {
      await isActiveCheckbox.uncheck();
      await expect(isActiveCheckbox).not.toBeChecked();
    } else {
      await isActiveCheckbox.check();
      await expect(isActiveCheckbox).toBeChecked();
    }
  });
});
