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

/**
 * Departments CRUD Tests
 *
 * Tests the Departments management functionality including:
 * - Viewing departments list
 * - Creating a new department
 * - Editing an existing department
 * - Deleting a department
 */

// 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 'D' + Date.now().toString().slice(-5);
}

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

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

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

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

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

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

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

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

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

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

    // Fill form fields
    const uniqueCode = generateUniqueCode();
    await page.locator('#addNewDepartmentForm #name').fill('Test Department');
    await page.locator('#addNewDepartmentForm #code').fill(uniqueCode);
    await page.locator('#addNewDepartmentForm #notes').fill('Test department description');

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

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

    // Verify success - check for SweetAlert or DataTable reload
    await page.waitForTimeout(1000);
    await expect(page.locator('.datatables-departments')).toBeVisible();
  });

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

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

    // Fill only code, leave name empty
    await page.locator('#addNewDepartmentForm #code').fill('TEST');

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

    // Form should show validation error or remain open
    await page.waitForTimeout(500);
    await expect(page.locator('#offcanvasAddDepartment')).toBeVisible();
  });

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

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

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

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

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

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

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

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

      // Verify offcanvas opens with Edit title
      await expect(page.locator('#offcanvasAddDepartment')).toBeVisible();

      // Verify the form has pre-filled data (name field should not be empty)
      const nameField = page.locator('#offcanvasAddDepartment #name');
      await page.waitForTimeout(500);
      const nameValue = await nameField.inputValue();
      expect(nameValue.length).toBeGreaterThan(0);

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

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

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

    // Find the delete button for a department
    const deleteButton = page.locator('.datatables-departments tbody tr .delete-department').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();
    }
  });
});
