import { test, expect } from '@playwright/test';
import {
  loginAsAdmin,
  generateUniqueName,
  generateUniqueEmail,
  generateUniquePhone,
  navigateToCompanies,
  navigateToCompanyCreate,
  confirmSweetAlert,
  waitForPageStable
} from '../helpers/crmcore';

/**
 * Companies CRUD Tests
 *
 * Tests the Company management functionality including:
 * - Viewing companies list page
 * - Creating a company with required fields
 * - Creating a company with all fields
 * - Viewing company details
 * - Editing an existing company
 * - Deleting a company with confirmation
 * - Searching companies in DataTable
 */

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

  test('should display companies list page', async ({ page }) => {
    await navigateToCompanies(page);

    // Verify page title
    await expect(page.locator('h4, h5').filter({ hasText: /companies/i }).first()).toBeVisible();

    // Verify card wrapper
    await expect(page.locator('.card').first()).toBeVisible();

    // Verify Add Company button exists
    const addButton = page.locator('a[href*="/companies/create"], button:has-text("Add")').first();
    await expect(addButton).toBeVisible();
  });

  test('should navigate to create company page', async ({ page }) => {
    await navigateToCompanies(page);

    // Click Add Company button
    const addButton = page.locator('a[href*="/companies/create"]').first();
    await addButton.click();

    // Verify form page loads
    await page.waitForURL('**/companies/create', { timeout: 10000 });
    await waitForPageStable(page);

    // Verify form is visible
    await expect(page.locator('form, #companyForm').first()).toBeVisible();
  });

  test('should create company with required fields', async ({ page }) => {
    await navigateToCompanyCreate(page);
    await waitForPageStable(page);

    // Fill required fields
    const companyName = generateUniqueName('Test Company');
    await page.locator('#name, input[name="name"]').first().fill(companyName);

    // Submit form
    await page.locator('button[type="submit"]').first().click();

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

    // Verify redirect to list or show page
    await page.waitForURL(/\/companies/, { timeout: 10000 });
  });

  test('should create company with all fields', async ({ page }) => {
    await navigateToCompanyCreate(page);
    await waitForPageStable(page);

    // Fill all fields
    const companyName = generateUniqueName('Full Company');
    const companyEmail = generateUniqueEmail();
    const companyPhone = generateUniquePhone();

    await page.locator('#name, input[name="name"]').first().fill(companyName);

    // Fill email if exists
    const emailField = page.locator('#email, input[name="email"]').first();
    if (await emailField.isVisible()) {
      await emailField.fill(companyEmail);
    }

    // Fill phone if exists
    const phoneField = page.locator('#phone, input[name="phone"]').first();
    if (await phoneField.isVisible()) {
      await phoneField.fill(companyPhone);
    }

    // Fill website if exists
    const websiteField = page.locator('#website, input[name="website"]').first();
    if (await websiteField.isVisible()) {
      await websiteField.fill('https://example.com');
    }

    // Fill address if exists
    const addressField = page.locator('#address, textarea[name="address"]').first();
    if (await addressField.isVisible()) {
      await addressField.fill('123 Test Street, Test City');
    }

    // Submit form
    await page.locator('button[type="submit"]').first().click();

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

    // Verify redirect
    await page.waitForURL(/\/companies/, { timeout: 10000 });
  });

  test('should show validation error for empty name', async ({ page }) => {
    await navigateToCompanyCreate(page);
    await waitForPageStable(page);

    // Leave name empty and submit
    await page.locator('button[type="submit"]').first().click();

    // Wait for validation
    await page.waitForTimeout(500);

    // Form should still be visible (validation failed)
    await expect(page.locator('form, #companyForm').first()).toBeVisible();

    // Should still be on create page
    expect(page.url()).toContain('/create');
  });

  test('should view company details', async ({ page }) => {
    await navigateToCompanies(page);
    await waitForPageStable(page);

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

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

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

    // Find and click view action
    const firstRow = rows.first();
    const dropdownToggle = firstRow.locator('.dropdown-toggle, button.btn-icon').first();

    if (await dropdownToggle.isVisible()) {
      await dropdownToggle.click();
      await page.waitForTimeout(300);

      const viewButton = page.locator('.dropdown-item:has-text("View"), a[href*="/companies/"][href$!="/edit"]').first();
      if (await viewButton.isVisible()) {
        await viewButton.click();
        await page.waitForURL(/\/companies\/\d+$/, { timeout: 10000 });
        await expect(page.locator('.card').first()).toBeVisible();
      }
    }
  });

  test('should edit existing company', async ({ page }) => {
    await navigateToCompanies(page);
    await waitForPageStable(page);

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

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

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

    // Find and click edit action
    const firstRow = rows.first();
    const dropdownToggle = firstRow.locator('.dropdown-toggle, button.btn-icon').first();

    if (await dropdownToggle.isVisible()) {
      await dropdownToggle.click();
      await page.waitForTimeout(300);

      const editButton = page.locator('.dropdown-item:has-text("Edit"), a[href*="/edit"]').first();
      if (await editButton.isVisible()) {
        await editButton.click();
        await page.waitForURL(/\/edit/, { timeout: 10000 });
        await waitForPageStable(page);

        // Modify name
        const updatedName = generateUniqueName('Updated Company');
        await page.locator('#name, input[name="name"]').first().fill(updatedName);

        // Save
        await page.locator('button[type="submit"]').first().click();
        await page.waitForLoadState('networkidle');

        // Verify redirect
        await page.waitForURL(/\/companies/, { timeout: 10000 });
      }
    }
  });

  test('should delete company with confirmation', async ({ page }) => {
    await navigateToCompanies(page);
    await waitForPageStable(page);

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

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

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

    // Find and click delete action
    const firstRow = rows.first();
    const dropdownToggle = firstRow.locator('.dropdown-toggle, button.btn-icon').first();

    if (await dropdownToggle.isVisible()) {
      await dropdownToggle.click();
      await page.waitForTimeout(300);

      const deleteButton = page.locator('.dropdown-item:has-text("Delete"), .dropdown-item.text-danger').first();
      if (await deleteButton.isVisible()) {
        await deleteButton.click();

        // Confirm deletion
        await confirmSweetAlert(page);
        await page.waitForTimeout(1000);

        // Table should still be visible
        await expect(page.locator('table').first()).toBeVisible();
      }
    }
  });

  test('should search companies in table', async ({ page }) => {
    await navigateToCompanies(page);
    await waitForPageStable(page);

    // Wait for table to load
    await page.waitForSelector('table', { timeout: 10000 });

    // Find search box
    const searchBox = page.locator('input[type="search"], .dataTables_filter input').first();

    if (await searchBox.isVisible()) {
      await searchBox.fill('test');
      await page.waitForTimeout(1000);

      // Table should still be visible
      await expect(page.locator('table').first()).toBeVisible();
    }
  });

  test('should cancel creation and return to list', async ({ page }) => {
    await navigateToCompanyCreate(page);
    await waitForPageStable(page);

    // Fill some data
    await page.locator('#name, input[name="name"]').first().fill('Will be cancelled');

    // Click cancel button
    const cancelButton = page.locator('a:has-text("Cancel"), a.btn-secondary, a.btn-label-secondary').first();
    if (await cancelButton.isVisible()) {
      await cancelButton.click();
      await page.waitForURL('**/companies', { timeout: 10000 });
      await expect(page.locator('.card').first()).toBeVisible();
    }
  });
});
