import { test, expect } from '@playwright/test';
import { loginAsAdmin } from './helpers/employee';

/**
 * Employee Edit Tests
 *
 * Tests the employee edit functionality including:
 * - Opening edit basic info offcanvas
 * - Opening edit work info offcanvas
 * - Updating employee information
 * - Closing offcanvas without saving
 */

// Find the first employee ID from the list to use for testing
async function getFirstEmployeeId(page): Promise<number | null> {
  await page.goto('/employees', { waitUntil: 'networkidle' });
  await page.waitForTimeout(1000);

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

  // Try to find a view link in the table
  const viewLink = page.locator('.datatables-users tbody tr:first-child a[href*="employees/view"]').first();

  if (await viewLink.count() > 0) {
    const href = await viewLink.getAttribute('href');
    if (href) {
      const match = href.match(/employees\/view\/(\d+)/);
      if (match) {
        return parseInt(match[1]);
      }
    }
  }

  return null;
}

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

  test('should open edit basic info offcanvas', async ({ page }) => {
    const employeeId = await getFirstEmployeeId(page);

    if (!employeeId) {
      test.skip();
      return;
    }

    await page.goto(`/employees/view/${employeeId}`, { waitUntil: 'networkidle' });

    // Check if Edit button exists (only for non-exited employees)
    const editBtn = page.locator('button.dropdown-toggle:has-text("Edit")');

    if (await editBtn.count() === 0) {
      test.skip(); // Employee is exited, cannot edit
      return;
    }

    // Open Edit dropdown
    await editBtn.click();
    await page.waitForTimeout(300);

    // Click Basic Information option
    await page.click('a[data-bs-target="#offcanvasEditBasicInfo"]');
    await page.waitForTimeout(500);

    // Verify offcanvas is visible
    await expect(page.locator('#offcanvasEditBasicInfo')).toBeVisible();

    // Verify form fields are visible
    await expect(page.locator('#offcanvasEditBasicInfo #firstName, #basicInfoForm #firstName').first()).toBeVisible();
  });

  test('should display pre-filled values in basic info form', async ({ page }) => {
    const employeeId = await getFirstEmployeeId(page);

    if (!employeeId) {
      test.skip();
      return;
    }

    await page.goto(`/employees/view/${employeeId}`, { waitUntil: 'networkidle' });

    const editBtn = page.locator('button.dropdown-toggle:has-text("Edit")');

    if (await editBtn.count() === 0) {
      test.skip();
      return;
    }

    // Open Edit dropdown and click Basic Information
    await editBtn.click();
    await page.waitForTimeout(300);
    await page.click('a[data-bs-target="#offcanvasEditBasicInfo"]');
    await page.waitForTimeout(500);

    // Verify form fields have values (not empty)
    const firstNameInput = page.locator('#offcanvasEditBasicInfo #firstName, #basicInfoForm #firstName').first();
    const firstNameValue = await firstNameInput.inputValue();
    expect(firstNameValue.length).toBeGreaterThan(0);
  });

  test('should close basic info offcanvas on cancel', async ({ page }) => {
    const employeeId = await getFirstEmployeeId(page);

    if (!employeeId) {
      test.skip();
      return;
    }

    await page.goto(`/employees/view/${employeeId}`, { waitUntil: 'networkidle' });

    const editBtn = page.locator('button.dropdown-toggle:has-text("Edit")');

    if (await editBtn.count() === 0) {
      test.skip();
      return;
    }

    // Open offcanvas
    await editBtn.click();
    await page.waitForTimeout(300);
    await page.click('a[data-bs-target="#offcanvasEditBasicInfo"]');
    await page.waitForTimeout(500);

    // Verify offcanvas is visible
    await expect(page.locator('#offcanvasEditBasicInfo')).toBeVisible();

    // Close offcanvas using close button
    await page.click('#offcanvasEditBasicInfo button[data-bs-dismiss="offcanvas"]');
    await page.waitForTimeout(500);

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

  test('should open edit work info offcanvas', async ({ page }) => {
    const employeeId = await getFirstEmployeeId(page);

    if (!employeeId) {
      test.skip();
      return;
    }

    await page.goto(`/employees/view/${employeeId}`, { waitUntil: 'networkidle' });

    const editBtn = page.locator('button.dropdown-toggle:has-text("Edit")');

    if (await editBtn.count() === 0) {
      test.skip();
      return;
    }

    // Open Edit dropdown
    await editBtn.click();
    await page.waitForTimeout(300);

    // Click Work Information option
    await page.click('a[data-bs-target="#offcanvasEditWorkInfo"]');
    await page.waitForTimeout(500);

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

  test('should close work info offcanvas on cancel', async ({ page }) => {
    const employeeId = await getFirstEmployeeId(page);

    if (!employeeId) {
      test.skip();
      return;
    }

    await page.goto(`/employees/view/${employeeId}`, { waitUntil: 'networkidle' });

    const editBtn = page.locator('button.dropdown-toggle:has-text("Edit")');

    if (await editBtn.count() === 0) {
      test.skip();
      return;
    }

    // Open offcanvas
    await editBtn.click();
    await page.waitForTimeout(300);
    await page.click('a[data-bs-target="#offcanvasEditWorkInfo"]');
    await page.waitForTimeout(500);

    // Verify offcanvas is visible
    await expect(page.locator('#offcanvasEditWorkInfo')).toBeVisible();

    // Close offcanvas
    await page.click('#offcanvasEditWorkInfo button[data-bs-dismiss="offcanvas"]');
    await page.waitForTimeout(500);

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

  test('should show required fields in basic info form', async ({ page }) => {
    const employeeId = await getFirstEmployeeId(page);

    if (!employeeId) {
      test.skip();
      return;
    }

    await page.goto(`/employees/view/${employeeId}`, { waitUntil: 'networkidle' });

    const editBtn = page.locator('button.dropdown-toggle:has-text("Edit")');

    if (await editBtn.count() === 0) {
      test.skip();
      return;
    }

    // Open offcanvas
    await editBtn.click();
    await page.waitForTimeout(300);
    await page.click('a[data-bs-target="#offcanvasEditBasicInfo"]');
    await page.waitForTimeout(500);

    // Verify required fields exist (marked with *)
    const formContainer = page.locator('#offcanvasEditBasicInfo, #basicInfoForm');
    await expect(formContainer.locator('label:has-text("First Name")').first()).toBeVisible();
    await expect(formContainer.locator('label:has-text("Last Name")').first()).toBeVisible();
    await expect(formContainer.locator('label:has-text("Email")').first()).toBeVisible();
  });
});
