import { test, expect } from '@playwright/test';
import {
  loginAsAdmin,
  navigateToProjects,
  waitForPageStable,
  waitForDataTable
} from './helpers/pmcore';

/**
 * PM Core Team Members Management Tests
 *
 * Tests the Project Team Members functionality including:
 * - Viewing team members section on project show page
 * - Adding team members modal
 * - Team member Select2 user search
 */

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

  test('should display team members section on project show page', async ({ page }) => {
    await test.step('Navigate to projects list', async () => {
      await navigateToProjects(page);
      await waitForPageStable(page);
      await waitForDataTable(page);
    });

    await test.step('Navigate to first project via dropdown action', async () => {
      const rows = page.locator('table tbody tr:not(.child)');
      const rowCount = await rows.count();

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

      const firstRow = rows.first();

      // Check if table is responsive (has expand control)
      const expandControl = firstRow.locator('.dtr-control, td.dtr-control').first();
      if (await expandControl.count() > 0 && await expandControl.isVisible()) {
        await expandControl.click();
        await page.waitForTimeout(300);
      }

      // Try to find dropdown toggle in main row or expanded child row
      let dropdownToggle = firstRow.locator('.dropdown-toggle, button.btn-icon').first();

      // If not visible in main row, check in child row (responsive expanded content)
      if (!await dropdownToggle.isVisible()) {
        const childRow = page.locator('table tbody tr.child').first();
        if (await childRow.count() > 0) {
          dropdownToggle = childRow.locator('.dropdown-toggle, button.btn-icon').first();
        }
      }

      await dropdownToggle.click({ force: true });
      await page.waitForTimeout(300);

      const viewButton = page.locator('.dropdown-menu.show').locator('a:has-text("View"), .dropdown-item:has-text("View")').first();
      await viewButton.click();

      await page.waitForURL(/\/projects\/\d+$/, { timeout: 10000 });
      await waitForPageStable(page);
    });

    await test.step('Verify Team Members section exists', async () => {
      const teamMembersCard = page.locator('.card').filter({ hasText: 'Team Members' }).first();
      await expect(teamMembersCard).toBeVisible({ timeout: 10000 });
    });

    await test.step('Verify Add Member button exists', async () => {
      const addMemberButton = page.locator('button[data-bs-target="#addMemberModal"], button:has-text("Add Member")').first();
      await expect(addMemberButton).toBeVisible();
    });
  });

  test('should open add member modal', async ({ page }) => {
    await test.step('Navigate to a project show page', async () => {
      await navigateToProjects(page);
      await waitForPageStable(page);
      await waitForDataTable(page);

      const rows = page.locator('table tbody tr:not(.child)');
      const rowCount = await rows.count();

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

      const firstRow = rows.first();

      // Handle responsive DataTable
      const expandControl = firstRow.locator('.dtr-control, td.dtr-control').first();
      if (await expandControl.count() > 0 && await expandControl.isVisible()) {
        await expandControl.click();
        await page.waitForTimeout(300);
      }

      let dropdownToggle = firstRow.locator('.dropdown-toggle, button.btn-icon').first();
      if (!await dropdownToggle.isVisible()) {
        const childRow = page.locator('table tbody tr.child').first();
        if (await childRow.count() > 0) {
          dropdownToggle = childRow.locator('.dropdown-toggle, button.btn-icon').first();
        }
      }

      await dropdownToggle.click({ force: true });
      await page.waitForTimeout(300);

      const viewButton = page.locator('.dropdown-menu.show').locator('a:has-text("View"), .dropdown-item:has-text("View")').first();
      await viewButton.click();

      await page.waitForURL(/\/projects\/\d+$/, { timeout: 10000 });
      await waitForPageStable(page);
    });

    await test.step('Click Add Member button', async () => {
      const addMemberButton = page.locator('button[data-bs-target="#addMemberModal"], button:has-text("Add Member")').first();
      await addMemberButton.click();
      await page.waitForTimeout(500);
    });

    await test.step('Verify modal opens', async () => {
      const modal = page.locator('#addMemberModal');
      await expect(modal).toBeVisible({ timeout: 5000 });
    });

    await test.step('Verify modal form elements', async () => {
      // User select
      const userSelect = page.locator('#member_user_id');
      await expect(userSelect).toBeVisible();

      // Role select
      const roleSelect = page.locator('#member_role');
      await expect(roleSelect).toBeVisible();

      // Submit button
      const submitButton = page.locator('#addMemberForm button[type="submit"]');
      await expect(submitButton).toBeVisible();
    });

    await test.step('Close modal', async () => {
      const closeButton = page.locator('#addMemberModal button.btn-close').first();
      await closeButton.click();
      await page.waitForTimeout(300);
    });
  });

  test('should have role options in add member modal', async ({ page }) => {
    await test.step('Navigate to a project show page', async () => {
      await navigateToProjects(page);
      await waitForPageStable(page);
      await waitForDataTable(page);

      const rows = page.locator('table tbody tr:not(.child)');
      if (await rows.count() === 0) {
        test.skip();
        return;
      }

      const firstRow = rows.first();
      const expandControl = firstRow.locator('.dtr-control, td.dtr-control').first();
      if (await expandControl.count() > 0 && await expandControl.isVisible()) {
        await expandControl.click();
        await page.waitForTimeout(300);
      }

      let dropdownToggle = firstRow.locator('.dropdown-toggle, button.btn-icon').first();
      if (!await dropdownToggle.isVisible()) {
        const childRow = page.locator('table tbody tr.child').first();
        if (await childRow.count() > 0) {
          dropdownToggle = childRow.locator('.dropdown-toggle, button.btn-icon').first();
        }
      }

      await dropdownToggle.click({ force: true });
      await page.waitForTimeout(300);

      const viewButton = page.locator('.dropdown-menu.show').locator('a:has-text("View"), .dropdown-item:has-text("View")').first();
      await viewButton.click();

      await page.waitForURL(/\/projects\/\d+$/, { timeout: 10000 });
      await waitForPageStable(page);
    });

    await test.step('Open Add Member modal', async () => {
      const addMemberButton = page.locator('button[data-bs-target="#addMemberModal"], button:has-text("Add Member")').first();
      await addMemberButton.click();
      await page.waitForTimeout(500);
    });

    await test.step('Verify role select has options', async () => {
      const roleSelect = page.locator('#member_role');
      const options = roleSelect.locator('option');
      const optionCount = await options.count();

      // Should have at least 2 role options (lead, member, etc.)
      expect(optionCount).toBeGreaterThanOrEqual(2);
    });

    await test.step('Close modal', async () => {
      const closeButton = page.locator('#addMemberModal button.btn-close').first();
      await closeButton.click();
    });
  });

  test('should display project information on show page', async ({ page }) => {
    await test.step('Navigate to a project show page', async () => {
      await navigateToProjects(page);
      await waitForPageStable(page);
      await waitForDataTable(page);

      const rows = page.locator('table tbody tr:not(.child)');
      if (await rows.count() === 0) {
        test.skip();
        return;
      }

      const firstRow = rows.first();
      const expandControl = firstRow.locator('.dtr-control, td.dtr-control').first();
      if (await expandControl.count() > 0 && await expandControl.isVisible()) {
        await expandControl.click();
        await page.waitForTimeout(300);
      }

      let dropdownToggle = firstRow.locator('.dropdown-toggle, button.btn-icon').first();
      if (!await dropdownToggle.isVisible()) {
        const childRow = page.locator('table tbody tr.child').first();
        if (await childRow.count() > 0) {
          dropdownToggle = childRow.locator('.dropdown-toggle, button.btn-icon').first();
        }
      }

      await dropdownToggle.click({ force: true });
      await page.waitForTimeout(300);

      const viewButton = page.locator('.dropdown-menu.show').locator('a:has-text("View"), .dropdown-item:has-text("View")').first();
      await viewButton.click();

      await page.waitForURL(/\/projects\/\d+$/, { timeout: 10000 });
      await waitForPageStable(page);
    });

    await test.step('Verify Project Information section', async () => {
      const projectInfoCard = page.locator('.card').filter({ hasText: 'Project Information' }).first();
      await expect(projectInfoCard).toBeVisible({ timeout: 10000 });
    });

    await test.step('Verify Budget Information section', async () => {
      const budgetInfoCard = page.locator('.card').filter({ hasText: 'Budget Information' }).first();
      await expect(budgetInfoCard).toBeVisible();
    });

    await test.step('Verify action buttons', async () => {
      const editButton = page.locator('a:has-text("Edit Project")').first();
      await expect(editButton).toBeVisible();
    });
  });
});
