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

/**
 * Teams CRUD Tests
 *
 * Tests the Teams management functionality including:
 * - Viewing teams list
 * - Creating a new team
 * - Editing an existing team
 * - Deleting a team
 * - Status toggle
 */

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

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

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

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

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

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

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

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

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

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

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

    // Fill form fields
    const uniqueCode = generateUniqueCode();
    await page.locator('#teamForm #name').fill('Test Team');
    await page.locator('#teamForm #code').fill(uniqueCode);
    await page.locator('#teamForm #notes').fill('Test team description');

    // Submit the form
    await page.locator('#teamForm .data-submit').click();

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

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

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

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

    // Clear any auto-generated code
    await page.locator('#teamForm #code').clear();

    // Try to submit empty form
    await page.locator('#teamForm .data-submit').click();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  test('should toggle team status', async ({ page }) => {
    await page.goto('/teams', { waitUntil: 'networkidle' });

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

    // Find the status toggle for a team (custom switch checkbox)
    const statusToggle = page.locator('.datatables-teams tbody tr .status-toggle').first();

    if (await statusToggle.count() > 0) {
      // Get initial state
      const wasChecked = await statusToggle.isChecked();

      // Toggle status - use force:true because checkbox is styled with overlay
      await statusToggle.click({ force: true });
      await page.waitForTimeout(1000);

      // Verify status changed
      const isChecked = await statusToggle.isChecked();
      expect(isChecked).not.toBe(wasChecked);

      // Toggle back to restore original state
      await statusToggle.click({ force: true });
      await page.waitForTimeout(500);
    }
  });
});
