import { test, expect } from '@playwright/test';
import {
  loginAsAdmin,
  generateUniqueName,
  navigateToCustomerGroups,
  waitForPageStable,
  confirmSweetAlert
} from '../helpers/crmcore';

/**
 * Customer Groups CRUD Tests
 *
 * Tests the Customer Group management functionality including:
 * - Viewing customer groups list page
 * - Creating a customer group via offcanvas form
 * - Editing an existing customer group
 * - Deleting a customer group with confirmation
 * - Viewing customer group statistics
 */

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

  test('should display customer groups list page', async ({ page }) => {
    await navigateToCustomerGroups(page);

    // Verify page title
    await expect(page.locator('h4, h5').filter({ hasText: /customer.*group/i }).first()).toBeVisible();

    // Verify card wrapper
    await expect(page.locator('.card').first()).toBeVisible();

    // Verify Add button exists
    const addButton = page.locator('button:has-text("Add"), a:has-text("Add")').first();
    await expect(addButton).toBeVisible();
  });

  test('should open customer group creation form', async ({ page }) => {
    await navigateToCustomerGroups(page);
    await waitForPageStable(page);

    // Click Add button
    const addButton = page.locator('button:has-text("Add"), a:has-text("Add")').first();
    await addButton.click();

    // Wait for offcanvas/dialog to open
    await page.waitForSelector('.offcanvas.show, dialog[open], .modal.show', { timeout: 5000 });

    // Verify form fields are visible
    await expect(page.locator('#name, input[name="name"]').first()).toBeVisible();
  });

  test('should create customer group with required fields', async ({ page }) => {
    await navigateToCustomerGroups(page);
    await waitForPageStable(page);

    // Click Add button
    const addButton = page.locator('button:has-text("Add"), a:has-text("Add")').first();
    await addButton.click();

    // Wait for form
    await page.waitForSelector('.offcanvas.show, dialog[open], .modal.show', { timeout: 5000 });
    await page.waitForTimeout(500);

    // Fill required fields
    const groupName = generateUniqueName('Test Group');
    await page.locator('#name, input[name="name"]').first().fill(groupName);

    // Submit form
    const saveButton = page.locator('button:has-text("Save"), button[type="submit"]').first();
    await saveButton.click();

    // Wait for response
    await page.waitForTimeout(2000);
  });

  test('should create customer group with description', async ({ page }) => {
    await navigateToCustomerGroups(page);
    await waitForPageStable(page);

    // Click Add button
    const addButton = page.locator('button:has-text("Add"), a:has-text("Add")').first();
    await addButton.click();

    // Wait for form
    await page.waitForSelector('.offcanvas.show, dialog[open], .modal.show', { timeout: 5000 });
    await page.waitForTimeout(500);

    // Fill all fields
    const groupName = generateUniqueName('Full Group');
    await page.locator('#name, input[name="name"]').first().fill(groupName);

    // Description
    const descField = page.locator('#description, textarea[name="description"]').first();
    if (await descField.isVisible()) {
      await descField.fill('Test customer group with description');
    }

    // Discount percentage if exists
    const discountField = page.locator('#discount_percentage, input[name="discount_percentage"]').first();
    if (await discountField.isVisible()) {
      await discountField.fill('10');
    }

    // Submit form
    const saveButton = page.locator('button:has-text("Save"), button[type="submit"]').first();
    await saveButton.click();

    // Wait for response
    await page.waitForTimeout(2000);
  });

  test('should edit existing customer group', async ({ page }) => {
    await navigateToCustomerGroups(page);
    await waitForPageStable(page);

    // Wait for table/list to load
    await page.waitForTimeout(1000);

    // Find edit button in table row or card
    const editButton = page.locator('.dropdown-item:has-text("Edit"), button:has-text("Edit"), a[href*="/edit"]').first();

    if (await editButton.isVisible()) {
      // If dropdown, open it first
      const dropdownToggle = page.locator('.dropdown-toggle, button.btn-icon').first();
      if (await dropdownToggle.isVisible()) {
        await dropdownToggle.click();
        await page.waitForTimeout(300);
      }

      await editButton.click();

      // Wait for edit form
      await page.waitForTimeout(1000);

      // Modify name
      const nameField = page.locator('#name, input[name="name"]').first();
      if (await nameField.isVisible()) {
        const updatedName = generateUniqueName('Updated Group');
        await nameField.fill(updatedName);

        // Save
        const saveButton = page.locator('button:has-text("Save"), button:has-text("Update")').first();
        await saveButton.click();
        await page.waitForTimeout(2000);
      }
    } else {
      test.skip();
    }
  });

  test('should delete customer group with confirmation', async ({ page }) => {
    await navigateToCustomerGroups(page);
    await waitForPageStable(page);

    // Wait for table/list to load
    await page.waitForTimeout(1000);

    // Find delete button
    const dropdownToggle = page.locator('.dropdown-toggle, button.btn-icon').first();

    if (await dropdownToggle.isVisible()) {
      await dropdownToggle.click();
      await page.waitForTimeout(300);

      const deleteButton = page.locator('.dropdown-item:has-text("Delete"), .dropdown-item.text-danger').first();
      if (await deleteButton.isVisible()) {
        await deleteButton.click();

        // Confirm deletion
        await confirmSweetAlert(page);
        await page.waitForTimeout(1000);

        // Page should still be functional
        await expect(page.locator('.card').first()).toBeVisible();
      }
    } else {
      test.skip();
    }
  });

  test('should display customer count per group', async ({ page }) => {
    await navigateToCustomerGroups(page);
    await waitForPageStable(page);

    // Wait for data to load
    await page.waitForTimeout(1000);

    // Verify table or list structure
    const table = page.locator('table').first();
    if (await table.isVisible()) {
      // Should have columns including customer count
      await expect(table).toBeVisible();
    }
  });
});
