import { test, expect } from '@playwright/test';
import {
  loginAsAdmin,
  navigateToSuppliers,
  navigateToSupplierShow,
  confirmSweetAlert,
  waitForPageStable,
  closeOffcanvas,
  waitForDataTableReload
} from '../helpers/systemcore';

/**
 * Supplier Addresses Management Tests
 *
 * Tests the Supplier Addresses functionality including:
 * - Viewing addresses section on supplier show page
 * - Opening add address offcanvas
 * - Creating addresses
 * - Editing existing addresses
 * - Deleting addresses with confirmation
 */

test.describe('Supplier Addresses', () => {
  let supplierId: number;

  test.beforeEach(async ({ page }) => {
    // Login as admin
    await loginAsAdmin(page);

    // Navigate to suppliers list
    await navigateToSuppliers(page);
    await waitForPageStable(page);

    // Wait for DataTable to load
    await waitForDataTableReload(page, '#suppliersTable');
    await page.waitForTimeout(1000);

    // Check if there are any suppliers in the table
    const rowCount = await page.locator('#suppliersTable tbody tr').count();
    const emptyTable = await page.locator('#suppliersTable tbody tr td.dataTables_empty').count();

    if (rowCount === 0 || emptyTable > 0) {
      // No suppliers available - tests will be skipped
      return;
    }

    // Get first supplier ID from the table
    const firstRow = page.locator('#suppliersTable tbody tr').first();
    const viewButton = firstRow.locator('a[href*="/systemcore/suppliers/"]').first();

    // Check if view button exists
    if (await viewButton.count() === 0) {
      return;
    }

    const href = await viewButton.getAttribute('href', { timeout: 5000 });

    if (href) {
      const matches = href.match(/\/systemcore\/suppliers\/(\d+)/);
      if (matches && matches[1]) {
        supplierId = parseInt(matches[1]);
      }
    }

    // Navigate to supplier show page
    if (supplierId) {
      await navigateToSupplierShow(page, supplierId);
      await waitForPageStable(page);
    }
  });

  test('should display addresses section on supplier show page', async ({ page }) => {
    // Skip if no supplier available
    if (!supplierId) {
      test.skip();
      return;
    }

    // Verify addresses card is visible (use first() to avoid matching multiple cards)
    const addressesCard = page.locator('.card:has-text("Addresses")').first();
    await expect(addressesCard).toBeVisible();

    // Verify Add button exists within the addresses card (use first() to handle multiple Add buttons)
    const addButton = addressesCard.locator('button:has-text("Add")').first();
    await expect(addButton).toBeVisible();
  });

  test('should open add address offcanvas', async ({ page }) => {
    // Skip if no supplier available
    if (!supplierId) {
      test.skip();
      return;
    }

    // Locate the addresses card and click Add button (use first() to handle multiple Add buttons)
    const addressesCard = page.locator('.card:has-text("Addresses")').first();
    await addressesCard.locator('button:has-text("Add")').first().click();
    await page.waitForTimeout(500);

    // Verify offcanvas opens
    const offcanvas = page.locator('#addressOffcanvas');
    await expect(offcanvas).toBeVisible();

    // Verify form fields are present
    await expect(page.locator('#address_line_1')).toBeVisible();
    await expect(page.locator('#address_city')).toBeVisible();
    await expect(page.locator('#address_country')).toBeVisible();

    // Close offcanvas
    await closeOffcanvas(page);
  });

  test('should create address for supplier', async ({ page }) => {
    // Skip if no supplier available
    if (!supplierId) {
      test.skip();
      return;
    }

    // Locate the addresses card and click Add button (use first() to handle multiple Add buttons)
    const addressesCard = page.locator('.card:has-text("Addresses")').first();
    await addressesCard.locator('button:has-text("Add")').first().click();
    await page.waitForTimeout(500);

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

    // Select address type
    await page.locator('#address_type').selectOption('office');

    // Fill address form
    await page.locator('#address_line_1').fill('789 Supplier Boulevard');
    await page.locator('#address_line_2').fill('Floor 5');
    await page.locator('#address_city').fill('Chicago');
    await page.locator('#address_state').fill('IL');
    await page.locator('#address_postal_code').fill('60601');
    await page.locator('#address_country').fill('USA');

    // Submit form
    await page.locator('#submitAddressBtn').click();

    // Wait for success
    await page.waitForTimeout(2000);

    // Verify address appears in the list
    await expect(addressesCard).toContainText('789 Supplier Boulevard');
  });

  test('should edit existing supplier address', async ({ page }) => {
    // Skip if no supplier available
    if (!supplierId) {
      test.skip();
      return;
    }

    // Locate the addresses card
    const addressesCard = page.locator('.card:has-text("Addresses")').first();

    // Check if there are any addresses
    const addressItems = addressesCard.locator('.col-md-6');
    const addressCount = await addressItems.count();

    if (addressCount === 0) {
      // Create an address first (use first() to handle multiple Add buttons)
      await addressesCard.locator('button:has-text("Add")').first().click();
      await page.waitForTimeout(500);
      await page.locator('#address_type').selectOption('office');
      await page.locator('#address_line_1').fill('Original Supplier Address');
      await page.locator('#address_city').fill('Miami');
      await page.locator('#address_country').fill('USA');
      await page.locator('#submitAddressBtn').click();
      await page.waitForTimeout(2000);
    }

    // Find and click edit button within the addresses card
    const dropdownToggle = addressesCard.locator('.dropdown-toggle').first();
    await dropdownToggle.click();
    await page.waitForTimeout(300);

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

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

    // Modify address line 1
    const addressLine1 = page.locator('#address_line_1');
    await addressLine1.clear();
    await addressLine1.fill('Updated Supplier Address');

    // Submit form
    await page.locator('#submitAddressBtn').click();

    // Wait for success
    await page.waitForTimeout(2000);

    // Verify changes appear
    await expect(addressesCard).toContainText('Updated Supplier Address');
  });

  test('should delete supplier address with confirmation', async ({ page }) => {
    // Skip if no supplier available
    if (!supplierId) {
      test.skip();
      return;
    }

    // Locate the addresses card
    const addressesCard = page.locator('.card:has-text("Addresses")').first();

    // Check if there's at least one address
    const addressItems = addressesCard.locator('.col-md-6');
    let addressCount = await addressItems.count();

    if (addressCount === 0) {
      // Create an address first (use first() to handle multiple Add buttons)
      await addressesCard.locator('button:has-text("Add")').first().click();
      await page.waitForTimeout(500);
      await page.locator('#address_type').selectOption('office');
      await page.locator('#address_line_1').fill('Address to Delete');
      await page.locator('#address_city').fill('Denver');
      await page.locator('#address_country').fill('USA');
      await page.locator('#submitAddressBtn').click();
      await page.waitForTimeout(2000);
    }

    // Find and click delete button within the addresses card
    const dropdownToggle = addressesCard.locator('.dropdown-toggle').first();
    await dropdownToggle.click();
    await page.waitForTimeout(300);

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

    // Confirm SweetAlert dialog
    await confirmSweetAlert(page);

    // Wait for deletion to complete
    await page.waitForTimeout(2000);
  });
});
