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

/**
 * Payment Terms CRUD Tests
 *
 * Tests the Payment Terms management functionality including:
 * - Viewing payment terms list page
 * - Navigating to create payment term page
 * - Creating a new payment term
 * - Validation errors for required fields
 * - Editing an existing payment term
 * - Deleting a payment term with confirmation
 */

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

  test('should display payment terms list page', async ({ page }) => {
    // Navigate to /systemcore/payment-terms
    await navigateToPaymentTerms(page);

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

    // Verify table is visible
    await expect(page.locator('#paymentTermsTable')).toBeVisible();

    // Verify Add Payment Term button exists
    const addButton = page.locator('a[href*="/systemcore/payment-terms/create"]');
    await expect(addButton).toBeVisible();
  });

  test('should navigate to create payment term page', async ({ page }) => {
    // Navigate to payment terms list
    await navigateToPaymentTerms(page);

    // Click "Add Payment Term" button
    await page.click('a[href*="/systemcore/payment-terms/create"]');

    // Verify redirects to create form
    await page.waitForURL('**/systemcore/payment-terms/create', { timeout: 10000 });
    await waitForPageStable(page);

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

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

  test('should create a new payment term', async ({ page }) => {
    // Navigate to create page
    await navigateToPaymentTermCreate(page);
    await waitForPageStable(page);

    // Fill: name
    await page.locator('#name').fill('Net 45');

    // Fill: code (unique)
    const uniqueCode = generateUniqueCode('PT');
    await page.locator('#code').fill(uniqueCode);

    // Fill: days
    await page.locator('#days').fill('45');

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

    // Fill optional description
    await page.locator('#description').fill('Payment due 45 days after invoice date');

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

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

    // Verify redirect to list page
    await page.waitForURL('**/systemcore/payment-terms**', { timeout: 10000 });
    const currentUrl = page.url();
    expect(currentUrl).toContain('/systemcore/payment-terms');
  });

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

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

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

    // Verify form is still visible (didn't submit)
    await expect(page.locator('#paymentTermForm')).toBeVisible();

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

  test('should edit existing payment term', async ({ page }) => {
    // Navigate to payment terms list
    await navigateToPaymentTerms(page);
    await waitForPageStable(page);

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

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

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

    // Modify name
    await page.locator('#name').fill('Updated Payment Term');

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

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

    // Verify redirect
    await page.waitForTimeout(1000);
    const currentUrl = page.url();
    expect(currentUrl).toContain('/systemcore/payment-terms');
  });

  test('should delete payment term with confirmation', async ({ page }) => {
    // Navigate to payment terms list
    await navigateToPaymentTerms(page);
    await waitForPageStable(page);

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

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

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

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

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

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

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

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

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