import { test, expect } from '@playwright/test';
import {
  loginAsAdmin,
  navigateToProjectStatuses,
  confirmSweetAlert,
  waitForSuccessSweetAlert,
  waitForPageStable
} from './helpers/pmcore';

/**
 * PM Core Project Status Configuration Tests
 *
 * Tests the Project Status management functionality including:
 * - Viewing status list with DataTable
 * - Creating custom project statuses
 * - Editing status details
 * - Deleting statuses
 */

test.describe('Project Status Configuration', () => {
  test.beforeEach(async ({ page }) => {
    await loginAsAdmin(page);
  });

  test('should display project status list', async ({ page }) => {
    await test.step('Navigate to project statuses page', async () => {
      await page.goto('/projects/project-statuses', { waitUntil: 'networkidle' });
      await waitForPageStable(page);
    });

    await test.step('Verify page loaded', async () => {
      await expect(page.locator('.card').first()).toBeVisible({ timeout: 15000 });
    });

    await test.step('Verify Add Status button exists', async () => {
      const addButton = page.locator('button:has-text("Add New Status"), button:has-text("Add")').first();
      await expect(addButton).toBeVisible();
    });

    await test.step('Verify table exists', async () => {
      const table = page.locator('table').first();
      await expect(table).toBeVisible();
    });
  });

  test('should create custom project status', async ({ page }) => {
    const statusName = `Test Status ${Date.now().toString().slice(-6)}`;

    await test.step('Navigate to project statuses page', async () => {
      await page.goto('/projects/project-statuses', { waitUntil: 'networkidle' });
      await waitForPageStable(page);
    });

    await test.step('Open create status form', async () => {
      const addButton = page.locator('button:has-text("Add New Status"), button:has-text("Add")').first();
      await addButton.click();
      await page.waitForTimeout(500);
    });

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

    await test.step('Fill status form', async () => {
      await page.locator('#statusName').fill(statusName);
      await page.locator('#statusColor').fill('#3498db');
    });

    await test.step('Submit form', async () => {
      await page.locator('#projectStatusForm button[type="submit"]').click();
      await waitForSuccessSweetAlert(page);
    });

    await test.step('Verify status created in table', async () => {
      await page.waitForTimeout(1000);
      const statusRow = page.locator('table tbody tr').filter({ hasText: statusName });
      await expect(statusRow.first()).toBeVisible();
    });
  });

  test('should edit project status', async ({ page }) => {
    await test.step('Navigate to project statuses page', async () => {
      await page.goto('/projects/project-statuses', { waitUntil: 'networkidle' });
      await waitForPageStable(page);
    });

    await test.step('Click edit action on first status', async () => {
      const rows = page.locator('table tbody tr');
      const rowCount = await rows.count();

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

      const firstRow = rows.first();
      const dropdownToggle = firstRow.locator('.dropdown-toggle, button.btn-icon').first();
      await dropdownToggle.click({ force: true });
      await page.waitForTimeout(300);

      const editButton = page.locator('.dropdown-menu.show .dropdown-item:has-text("Edit")').first();
      await editButton.click();
      await page.waitForTimeout(500);
    });

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

    await test.step('Modify status details', async () => {
      const nameField = page.locator('#statusName');
      const currentValue = await nameField.inputValue();
      await nameField.fill(currentValue + ' (Updated)');
    });

    await test.step('Save changes', async () => {
      await page.locator('#projectStatusForm button[type="submit"]').click();
      await waitForSuccessSweetAlert(page);
    });
  });

  test('should delete project status', async ({ page }) => {
    const statusName = `Delete Status ${Date.now().toString().slice(-6)}`;

    await test.step('Create a status to delete', async () => {
      await page.goto('/projects/project-statuses', { waitUntil: 'networkidle' });
      await waitForPageStable(page);

      const addButton = page.locator('button:has-text("Add New Status"), button:has-text("Add")').first();
      await addButton.click();
      await page.waitForTimeout(500);

      await page.locator('#statusName').fill(statusName);
      await page.locator('#statusColor').fill('#ff0000');
      await page.locator('#projectStatusForm button[type="submit"]').click();
      await waitForSuccessSweetAlert(page);
    });

    await test.step('Navigate to project statuses page', async () => {
      await page.goto('/projects/project-statuses', { waitUntil: 'networkidle' });
      await waitForPageStable(page);
    });

    await test.step('Click delete action', async () => {
      await page.waitForTimeout(1000);
      const statusRow = page.locator('table tbody tr').filter({ hasText: statusName }).first();

      if (await statusRow.isVisible()) {
        const dropdownToggle = statusRow.locator('.dropdown-toggle, button.btn-icon').first();
        await dropdownToggle.click({ force: true });
        await page.waitForTimeout(300);

        const deleteButton = page.locator('.dropdown-menu.show .dropdown-item:has-text("Delete")').first();
        await deleteButton.click();
        await page.waitForTimeout(300);
      } else {
        test.skip();
      }
    });

    await test.step('Confirm deletion', async () => {
      await confirmSweetAlert(page);
      await waitForSuccessSweetAlert(page);
    });
  });

  test('should show validation when name is empty', async ({ page }) => {
    await test.step('Navigate to project statuses page', async () => {
      await page.goto('/projects/project-statuses', { waitUntil: 'networkidle' });
      await waitForPageStable(page);
    });

    await test.step('Open create form', async () => {
      const addButton = page.locator('button:has-text("Add New Status"), button:has-text("Add")').first();
      await addButton.click();
      await page.waitForTimeout(500);
    });

    await test.step('Try to submit empty form', async () => {
      // Clear any default values
      await page.locator('#statusName').fill('');
      await page.locator('#projectStatusForm button[type="submit"]').click();
      await page.waitForTimeout(500);
    });

    await test.step('Verify form is still open (validation prevented submission)', async () => {
      // Form should still be visible because validation failed
      const nameField = page.locator('#statusName');
      await expect(nameField).toBeVisible();
    });
  });

  test('should close offcanvas on cancel', async ({ page }) => {
    await test.step('Navigate to project statuses page', async () => {
      await page.goto('/projects/project-statuses', { waitUntil: 'networkidle' });
      await waitForPageStable(page);
    });

    await test.step('Open create form', async () => {
      const addButton = page.locator('button:has-text("Add New Status"), button:has-text("Add")').first();
      await addButton.click();
      await page.waitForTimeout(500);
    });

    await test.step('Verify offcanvas is open', async () => {
      const offcanvas = page.locator('.offcanvas.show');
      await expect(offcanvas).toBeVisible({ timeout: 5000 });
    });

    await test.step('Click cancel button', async () => {
      const cancelButton = page.locator('.offcanvas.show button:has-text("Cancel"), .offcanvas.show .btn-label-secondary').first();
      await cancelButton.click();
      await page.waitForTimeout(500);
    });

    await test.step('Verify offcanvas closed', async () => {
      const offcanvas = page.locator('.offcanvas.show');
      await expect(offcanvas).not.toBeVisible({ timeout: 5000 });
    });
  });
});
