import { test, expect } from '@playwright/test';
import {
  loginAsAdmin,
  generateUniqueName,
  generateUniqueEmail,
  generateUniquePhone,
  navigateToCRMCustomers,
  navigateToCRMCustomerCreate,
  waitForPageStable,
  confirmSweetAlert
} from '../helpers/crmcore';

/**
 * CRM Customers CRUD Tests
 *
 * Tests the CRM Customer management functionality including:
 * - Viewing customers list page
 * - Creating a customer with required fields
 * - Creating a customer with all fields
 * - Viewing customer details
 * - Editing an existing customer
 * - Toggling customer blacklist status
 * - Searching customers in DataTable
 * - Filtering customers by type/status
 */

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

  test('should display customers list page', async ({ page }) => {
    await navigateToCRMCustomers(page);

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

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

  test('should display customer statistics cards', async ({ page }) => {
    await navigateToCRMCustomers(page);
    await waitForPageStable(page);

    // Look for statistics cards (Total, Active, etc.)
    const statsCards = page.locator('.card .card-body h4, .card .card-body .h4');
    const count = await statsCards.count();

    // Should have some stats
    expect(count).toBeGreaterThanOrEqual(0);
  });

  test('should display customer type filter', async ({ page }) => {
    await navigateToCRMCustomers(page);
    await waitForPageStable(page);

    // Look for customer type filter
    const typeFilter = page.locator('select:has(option:has-text("B2B")), .select2-container').first();
    await expect(typeFilter).toBeVisible();
  });

  test('should navigate to create customer page', async ({ page }) => {
    await navigateToCRMCustomers(page);
    await waitForPageStable(page);

    // Click Add Customer button
    const addButton = page.locator('a[href*="/customers/create"], button:has-text("Add")').first();
    await addButton.click();

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

    // Verify form is visible
    await expect(page.locator('form').first()).toBeVisible();
  });

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

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

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

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

    // Verify redirect
    await page.waitForURL(/\/customers/, { timeout: 10000 });
  });

  test('should create customer with all fields', async ({ page }) => {
    await navigateToCRMCustomerCreate(page);
    await waitForPageStable(page);

    // Fill all fields
    const customerName = generateUniqueName('Full Customer');
    const customerEmail = generateUniqueEmail();
    const customerPhone = generateUniquePhone();

    await page.locator('#name, input[name="name"]').first().fill(customerName);

    // Email
    const emailField = page.locator('#email, input[name="email"]').first();
    if (await emailField.isVisible()) {
      await emailField.fill(customerEmail);
    }

    // Phone
    const phoneField = page.locator('#phone, input[name="phone"]').first();
    if (await phoneField.isVisible()) {
      await phoneField.fill(customerPhone);
    }

    // Customer type
    const typeSelect = page.locator('#customer_type, select[name="customer_type"]').first();
    if (await typeSelect.isVisible()) {
      await typeSelect.selectOption({ index: 1 });
    }

    // Company name
    const companyField = page.locator('#company_name, input[name="company_name"]').first();
    if (await companyField.isVisible()) {
      await companyField.fill('Test Corp');
    }

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

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

    // Verify redirect
    await page.waitForURL(/\/customers/, { timeout: 10000 });
  });

  test('should view customer details', async ({ page }) => {
    await navigateToCRMCustomers(page);
    await waitForPageStable(page);

    // Wait for table to load
    await page.waitForSelector('table tbody tr', { timeout: 10000 });

    const rows = page.locator('table tbody tr');
    const rowCount = await rows.count();

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

    // Find and click view action
    const firstRow = rows.first();
    const dropdownToggle = firstRow.locator('.dropdown-toggle, button.btn-icon').first();

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

      const viewButton = page.locator('.dropdown-item:has-text("View")').first();
      if (await viewButton.isVisible()) {
        await viewButton.click();
        await page.waitForURL(/\/customers\/\d+$/, { timeout: 10000 });
        await expect(page.locator('.card').first()).toBeVisible();
      }
    }
  });

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

    // Wait for table to load
    await page.waitForSelector('table tbody tr', { timeout: 10000 });

    const rows = page.locator('table tbody tr');
    const rowCount = await rows.count();

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

    // Find and click edit action
    const firstRow = rows.first();
    const dropdownToggle = firstRow.locator('.dropdown-toggle, button.btn-icon').first();

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

      const editButton = page.locator('.dropdown-item:has-text("Edit"), a[href*="/edit"]').first();
      if (await editButton.isVisible()) {
        await editButton.click();

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

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

        // Save
        await page.locator('button[type="submit"]').first().click();
        await page.waitForLoadState('networkidle');

        // Verify redirect
        await page.waitForURL(/\/customers/, { timeout: 10000 });
      }
    }
  });

  test('should filter customers by type', async ({ page }) => {
    await navigateToCRMCustomers(page);
    await waitForPageStable(page);

    // Find type filter
    const typeFilter = page.locator('select:has(option:has-text("B2B"))').first();

    if (await typeFilter.isVisible()) {
      await typeFilter.selectOption({ index: 1 });
      await page.waitForTimeout(1000);

      // Table should still be visible
      await expect(page.locator('table').first()).toBeVisible();
    }
  });

  test('should search customers in table', async ({ page }) => {
    await navigateToCRMCustomers(page);
    await waitForPageStable(page);

    // Find search box
    const searchBox = page.locator('input[type="search"], .dataTables_filter input').first();

    if (await searchBox.isVisible()) {
      await searchBox.fill('test');
      await page.waitForTimeout(1000);

      // Table should still be visible
      await expect(page.locator('table').first()).toBeVisible();
    }
  });

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

    // Fill some data
    await page.locator('#name, input[name="name"]').first().fill('Will be cancelled');

    // Click cancel button
    const cancelButton = page.locator('a:has-text("Cancel"), a.btn-secondary').first();
    if (await cancelButton.isVisible()) {
      await cancelButton.click();
      await page.waitForURL('**/customers', { timeout: 10000 });
      await expect(page.locator('.card').first()).toBeVisible();
    }
  });
});
