import { Page } from '@playwright/test';

/**
 * WMS Inventory Core Test Helper Functions
 *
 * Shared utilities for WMS Inventory Core module Playwright tests
 */

/**
 * Login as admin user
 */
export async function loginAsAdmin(page: Page) {
  await page.goto('/auth/login');
  await page.locator('#email').fill('admin@demo.com');
  await page.locator('#password').fill('password123');
  await page.locator('button[type="submit"]').click();
  await page.waitForURL('**/dashboard', { timeout: 15000 });
}

/**
 * Generate unique code with prefix
 */
export function generateUniqueCode(prefix: string = 'WMS') {
  return prefix + Date.now().toString().slice(-6);
}

/**
 * Generate unique name with prefix
 */
export function generateUniqueName(prefix: string = 'Test') {
  return `${prefix} ${Date.now().toString().slice(-4)}`;
}

/**
 * Confirm SweetAlert dialog
 */
export async function confirmSweetAlert(page: Page) {
  await page.waitForSelector('.swal2-popup', { state: 'visible', timeout: 5000 });
  await page.click('.swal2-confirm');
  await page.waitForTimeout(500);
}

/**
 * Cancel SweetAlert dialog
 */
export async function cancelSweetAlert(page: Page) {
  await page.waitForSelector('.swal2-popup', { state: 'visible', timeout: 5000 });
  await page.click('.swal2-cancel');
  await page.waitForTimeout(500);
}

/**
 * Wait for success SweetAlert and dismiss it
 */
export async function waitForSuccessSweetAlert(page: Page) {
  await page.waitForSelector('.swal2-popup.swal2-icon-success, .swal2-success', { state: 'visible', timeout: 10000 });
  const okButton = page.locator('.swal2-confirm');
  if (await okButton.isVisible()) {
    await okButton.click();
  }
  await page.waitForTimeout(500);
}

/**
 * Wait for DataTable to reload
 */
export async function waitForDataTableReload(page: Page, tableSelector: string) {
  await page.waitForLoadState('networkidle');
  await page.waitForTimeout(500);
  await page.waitForSelector(tableSelector, { timeout: 10000 });
}

/**
 * Wait for page to be fully loaded and stable
 */
export async function waitForPageStable(page: Page) {
  await page.waitForLoadState('networkidle');
  await page.waitForTimeout(500);
}

/**
 * Check if an element exists on the page
 */
export async function elementExists(page: Page, selector: string): Promise<boolean> {
  return await page.locator(selector).count() > 0;
}

// ============================================
// Navigation Helpers
// ============================================

/**
 * Navigate to WMS Inventory dashboard
 */
export async function navigateToDashboard(page: Page) {
  await page.goto('/inventory/dashboard');
  await waitForPageStable(page);
}

/**
 * Navigate to Products list page
 */
export async function navigateToProducts(page: Page) {
  await page.goto('/inventory/products');
  await page.waitForSelector('#products-table', { timeout: 10000 });
}

/**
 * Navigate to Adjustments list page
 */
export async function navigateToAdjustments(page: Page) {
  await page.goto('/inventory/adjustments');
  await page.waitForSelector('.card-datatable, table', { timeout: 10000 });
}

/**
 * Navigate to Transfers list page
 */
export async function navigateToTransfers(page: Page) {
  await page.goto('/inventory/transfers');
  await page.waitForSelector('.card-datatable, table', { timeout: 10000 });
}

/**
 * Navigate to Warehouses list page
 */
export async function navigateToWarehouses(page: Page) {
  await page.goto('/inventory/warehouses');
  await page.waitForSelector('.card-datatable, table', { timeout: 10000 });
}

/**
 * Navigate to Categories list page
 */
export async function navigateToCategories(page: Page) {
  await page.goto('/inventory/categories');
  await page.waitForSelector('.datatables-categories, table', { timeout: 10000 });
}

// ============================================
// Adjustment-Specific Helpers
// ============================================

/**
 * Find adjustment row by status
 */
export async function findAdjustmentRowByStatus(page: Page, status: string): Promise<number> {
  const rows = page.locator('table tbody tr');
  const count = await rows.count();

  for (let i = 0; i < count; i++) {
    const row = rows.nth(i);
    const statusBadge = row.locator('.badge');
    const badgeText = await statusBadge.textContent();

    if (badgeText?.toUpperCase().includes(status.toUpperCase())) {
      return i;
    }
  }

  return -1;
}

/**
 * Approve an adjustment from detail page
 */
export async function approveAdjustment(page: Page) {
  const approveButton = page.locator('#approve-adjustment, button:has-text("Approve")').first();
  await approveButton.click();
  await confirmSweetAlert(page);
  await page.waitForTimeout(1000);
}

// ============================================
// Transfer-Specific Helpers
// ============================================

/**
 * Find transfer row by status
 */
export async function findTransferRowByStatus(page: Page, status: string): Promise<number> {
  const rows = page.locator('table tbody tr');
  const count = await rows.count();

  for (let i = 0; i < count; i++) {
    const row = rows.nth(i);
    const statusBadge = row.locator('.badge');
    const badgeText = await statusBadge.textContent();

    if (badgeText?.toUpperCase().includes(status.toUpperCase())) {
      return i;
    }
  }

  return -1;
}
