import { test, expect } from '@playwright/test';
import {
  loginAsAdmin,
  generateUniqueCode,
  navigateToTaxConfigurations,
  navigateToTaxConfigurationCreate,
  confirmSweetAlert,
  waitForPageStable
} from '../helpers/systemcore';

/**
 * Tax Configurations CRUD Tests
 *
 * Tests the Tax Configurations management functionality including:
 * - Viewing tax configurations list page
 * - Creating a new tax configuration
 * - Validating rate range (0-100)
 * - Editing an existing tax configuration
 * - Deleting a tax configuration with confirmation
 */

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

  test('should display tax configurations list page', async ({ page }) => {
    // Navigate to tax configurations page
    await navigateToTaxConfigurations(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('#taxConfigurationsTable')).toBeVisible();

    // Verify Add Tax Configuration button exists
    const addButton = page.locator('a[href*="/systemcore/tax-configurations/create"]');
    await expect(addButton).toBeVisible();
  });

  test('should navigate to create tax configuration page', async ({ page }) => {
    await navigateToTaxConfigurations(page);

    // Click "Add Tax Configuration" button
    await page.click('a[href*="/systemcore/tax-configurations/create"]');

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

    // Verify form is visible
    await expect(page.locator('#taxConfigurationForm')).toBeVisible();
    await expect(page.locator('#name')).toBeVisible();
    await expect(page.locator('#code')).toBeVisible();
    await expect(page.locator('#rate')).toBeVisible();
  });

  test('should create a new tax configuration', async ({ page }) => {
    await navigateToTaxConfigurationCreate(page);

    // Generate unique code
    const uniqueCode = generateUniqueCode('TAX');
    const taxName = 'VAT 10%';
    const taxRate = '10';

    // Fill form fields
    await page.locator('#name').fill(taxName);
    await page.locator('#code').fill(uniqueCode);
    await page.locator('#rate').fill(taxRate);

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

    // Optional: fill description
    await page.locator('#description').fill('Test tax configuration for 10% VAT');

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

    // Wait for navigation back to index
    await page.waitForURL('**/systemcore/tax-configurations', { timeout: 10000 });
    await waitForPageStable(page);

    // Verify success - table should be visible
    await expect(page.locator('#taxConfigurationsTable')).toBeVisible();
  });

  test('should validate rate max value (100)', async ({ page }) => {
    await navigateToTaxConfigurationCreate(page);

    // Fill basic fields
    await page.locator('#name').fill('Invalid Tax Rate High');
    await page.locator('#code').fill(generateUniqueCode('TAX'));

    // Try to enter rate > 100
    await page.locator('#rate').fill('150');

    // Check HTML5 validation - the input has min=0 max=100
    const rateInput = page.locator('#rate');
    const maxValue = await rateInput.getAttribute('max');
    expect(maxValue).toBe('100');

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

    // Wait a moment to check if form submission prevented
    await page.waitForTimeout(1000);

    // Form should still be on create page
    const currentUrl = page.url();
    expect(currentUrl).toContain('tax-configurations/create');
  });

  test('should validate rate min value (0)', async ({ page }) => {
    await navigateToTaxConfigurationCreate(page);

    // Fill basic fields
    await page.locator('#name').fill('Invalid Tax Rate Low');
    await page.locator('#code').fill(generateUniqueCode('TAX'));

    // Try to enter rate < 0
    await page.locator('#rate').fill('-5');

    // Check HTML5 validation
    const rateInput = page.locator('#rate');
    const minValue = await rateInput.getAttribute('min');
    expect(minValue).toBe('0');

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

    // Wait a moment
    await page.waitForTimeout(1000);

    // Form should still be on create page
    const currentUrl = page.url();
    expect(currentUrl).toContain('tax-configurations/create');
  });

  test('should validate required fields', async ({ page }) => {
    await navigateToTaxConfigurationCreate(page);

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

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

    // Form should still be on create page due to HTML5 validation
    const currentUrl = page.url();
    expect(currentUrl).toContain('tax-configurations/create');

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

  test('should edit existing tax configuration', async ({ page }) => {
    // Navigate to tax configurations list
    await navigateToTaxConfigurations(page);
    await waitForPageStable(page);

    // Wait for DataTable to load
    await page.waitForTimeout(2000);

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

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

    // Modify rate
    const newRate = '20';
    await page.locator('#rate').fill(newRate);

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

    // Wait for navigation back to index
    await page.waitForURL('**/systemcore/tax-configurations', { timeout: 10000 });
    await waitForPageStable(page);

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

  test('should delete tax configuration with confirmation', async ({ page }) => {
    // Navigate to tax configurations list
    await navigateToTaxConfigurations(page);
    await waitForPageStable(page);

    // Wait for DataTable to load
    await page.waitForTimeout(2000);

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

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

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

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

    // Wait for deletion to complete
    await page.waitForTimeout(1500);

    // Verify table reloaded
    await expect(page.locator('#taxConfigurationsTable')).toBeVisible();
  });

  test('should handle decimal rates correctly', async ({ page }) => {
    await navigateToTaxConfigurationCreate(page);

    const uniqueCode = generateUniqueCode('TAX');
    const decimalRate = '12.5';

    await page.locator('#name').fill('GST 12.5%');
    await page.locator('#code').fill(uniqueCode);
    await page.locator('#rate').fill(decimalRate);

    // Verify input accepts decimal
    const rateInput = page.locator('#rate');
    const stepValue = await rateInput.getAttribute('step');
    expect(stepValue).toBe('0.01');

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

    // Wait for success
    await page.waitForURL('**/systemcore/tax-configurations', { timeout: 10000 });
    await waitForPageStable(page);

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

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

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

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

    // Should navigate back to list
    await page.waitForURL('**/systemcore/tax-configurations', { timeout: 10000 });
    await waitForPageStable(page);

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