import { test, expect } from '@playwright/test';

/**
 * Designations CRUD Tests
 *
 * Tests the Designations management functionality including:
 * - Viewing designations list
 * - Creating a new designation
 * - Editing an existing designation
 * - Deleting a designation
 */

// Helper function to login as admin
async function loginAsAdmin(page) {
  await page.goto('/auth/login', { waitUntil: 'networkidle' });
  await page.locator('#email').fill('admin@demo.com');
  await page.locator('#password').fill('password123');
  await page.locator('button[type="submit"]').click();
  await page.waitForURL('**/dashboard', { timeout: 15000 });
}

// Generate unique code for tests
function generateUniqueCode() {
  return 'DES' + Date.now().toString().slice(-5);
}

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

  test('should display designations list page', async ({ page }) => {
    // Navigate to designations page
    await page.goto('/designations', { waitUntil: 'networkidle' });

    // Verify page elements
    await expect(page.locator('.card')).toBeVisible();
    await expect(page.locator('.datatables-designations')).toBeVisible();

    // Verify Add New button exists
    await expect(page.locator('.add-new-designation')).toBeVisible();
  });

  test('should open add designation offcanvas', async ({ page }) => {
    await page.goto('/designations', { waitUntil: 'networkidle' });

    // Click Add New Designation button
    await page.locator('.add-new-designation').click();

    // Wait for offcanvas to open
    await expect(page.locator('#offcanvasAddOrUpdateDesignation')).toBeVisible();

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

  test('should create a new designation', async ({ page }) => {
    await page.goto('/designations', { waitUntil: 'networkidle' });

    // Open add designation offcanvas
    await page.locator('.add-new-designation').click();
    await expect(page.locator('#offcanvasAddOrUpdateDesignation')).toBeVisible();

    // Fill form fields
    const uniqueCode = generateUniqueCode();
    await page.locator('#designationForm #name').fill('Test Manager');
    await page.locator('#designationForm #code').fill(uniqueCode);
    await page.locator('#designationForm #notes').fill('Test designation description');

    // Submit the form
    await page.locator('#designationForm button[type="submit"], #designationForm .data-submit').first().click();

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

    // Verify DataTable is still visible (form processed)
    await page.waitForTimeout(1000);
    await expect(page.locator('.datatables-designations')).toBeVisible();
  });

  test('should show validation error for empty required fields', async ({ page }) => {
    await page.goto('/designations', { waitUntil: 'networkidle' });

    // Open add designation offcanvas
    await page.locator('.add-new-designation').click();
    await expect(page.locator('#offcanvasAddOrUpdateDesignation')).toBeVisible();

    // Try to submit empty form
    await page.locator('#designationForm button[type="submit"], #designationForm .data-submit').first().click();

    // Form should remain open with validation errors
    await page.waitForTimeout(500);
    await expect(page.locator('#offcanvasAddOrUpdateDesignation')).toBeVisible();
  });

  test('should close offcanvas on cancel', async ({ page }) => {
    await page.goto('/designations', { waitUntil: 'networkidle' });

    // Open add designation offcanvas
    await page.locator('.add-new-designation').click();
    await expect(page.locator('#offcanvasAddOrUpdateDesignation')).toBeVisible();

    // Click cancel button
    await page.locator('#offcanvasAddOrUpdateDesignation button[data-bs-dismiss="offcanvas"]').first().click();

    // Verify offcanvas is hidden
    await expect(page.locator('#offcanvasAddOrUpdateDesignation')).toBeHidden({ timeout: 5000 });
  });

  test('should open edit designation offcanvas', async ({ page }) => {
    await page.goto('/designations', { waitUntil: 'networkidle' });

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

    // Find and click the first edit button
    const editButton = page.locator('.datatables-designations tbody tr .edit-record').first();

    if (await editButton.count() > 0) {
      await editButton.click();
      await page.waitForTimeout(500);

      // Verify offcanvas opens
      await expect(page.locator('#offcanvasAddOrUpdateDesignation')).toBeVisible();

      // Verify the form has pre-filled data
      const nameField = page.locator('#offcanvasAddOrUpdateDesignation #name, #designationForm #name').first();
      await page.waitForTimeout(500);
      const nameValue = await nameField.inputValue();
      expect(nameValue.length).toBeGreaterThan(0);

      // Close offcanvas
      await page.locator('#offcanvasAddOrUpdateDesignation button[data-bs-dismiss="offcanvas"]').first().click();
    }
  });

  test('should delete designation with confirmation', async ({ page }) => {
    await page.goto('/designations', { waitUntil: 'networkidle' });

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

    // Find the delete button
    const deleteButton = page.locator('.datatables-designations tbody tr .delete-record').first();

    if (await deleteButton.count() > 0) {
      await deleteButton.click();

      // Wait for SweetAlert2 confirmation dialog
      await page.waitForSelector('.swal2-popup', { state: 'visible', timeout: 5000 });

      // Verify SweetAlert2 dialog content
      await expect(page.locator('.swal2-title')).toContainText('Are you sure');

      // Click Cancel to dismiss without deleting
      await page.locator('.swal2-cancel').click();
      await page.waitForTimeout(500);

      // Verify SweetAlert2 is closed
      await expect(page.locator('.swal2-popup')).toBeHidden();
    }
  });
});
