import { test, expect } from '@playwright/test';
import {
  loginAsAdmin,
  generateUniqueName,
  generateUniqueEmail,
  generateUniquePhone,
  navigateToSuppliers,
  navigateToSupplierCreate,
  confirmSweetAlert,
  waitForPageStable,
  waitForDataTableReload
} from '../helpers/systemcore';

/**
 * Suppliers CRUD Tests
 *
 * Tests the Supplier management functionality including:
 * - Viewing suppliers list page
 * - Creating a supplier with required fields
 * - Creating a supplier with all fields
 * - Validation errors for required fields
 * - Viewing supplier details
 * - Editing an existing supplier
 * - Deleting a supplier with confirmation
 */

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

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

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

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

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

  test('should navigate to create supplier page', async ({ page }) => {
    // Navigate to suppliers list
    await navigateToSuppliers(page);

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

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

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

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

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

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

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

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

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

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

    // Fill all fields
    const supplierName = generateUniqueName('Complete Supplier');
    const supplierEmail = generateUniqueEmail();
    const supplierPhone = generateUniquePhone();

    await page.locator('#name').fill(supplierName);
    await page.locator('#company_name').fill('Supplier Company Ltd');
    await page.locator('#email').fill(supplierEmail);
    await page.locator('#phone').fill(supplierPhone);
    await page.locator('#mobile').fill('+1555' + Date.now().toString().slice(-7));
    await page.locator('#website').fill('https://supplier-example.com');
    await page.locator('#tax_id').fill('STAX' + Date.now().toString().slice(-6));
    await page.locator('#credit_limit').fill('100000');
    await page.locator('#notes').fill('Test supplier created via E2E test');

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

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

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

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

    // Submit without name
    await page.locator('#supplierForm button[type="submit"]').click();

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

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

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

  test('should view supplier details', async ({ page }) => {
    // Navigate to suppliers list
    await navigateToSuppliers(page);
    await waitForPageStable(page);

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

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

    // Get the first row
    const firstRow = page.locator('#suppliersTable 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/suppliers/"]:not([href*="/edit"])').first();
    const viewButtonCount = await viewButton.count();

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

    await viewButton.click();

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

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

  test('should edit existing supplier', async ({ page }) => {
    // Navigate to suppliers list
    await navigateToSuppliers(page);
    await waitForPageStable(page);

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

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

    // Get the first row
    const firstRow = page.locator('#suppliersTable 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('#supplierForm')).toBeVisible();

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

    // Save and verify changes
    await page.locator('#supplierForm 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\/suppliers/);
  });

  test('should delete supplier with confirmation', async ({ page }) => {
    // Navigate to suppliers list
    await navigateToSuppliers(page);
    await waitForPageStable(page);

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

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

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

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

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

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

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

    // 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/suppliers', { timeout: 10000 });
    await waitForPageStable(page);

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