/**
 * User Links E2E Tests
 * Tests the complete user links feature in staff dashboard
 */

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

// Staff credentials
const STAFF_USERNAME = 'asim';
const STAFF_PASSWORD = 'AsimMawidi2025!';
const BASE_URL = 'http://localhost:9000';

// Helper function to login as staff
async function loginAsStaff(page: Page) {
  await page.goto(`${BASE_URL}/staff/login`);
  await page.fill('input[name="username"], input[type="text"]', STAFF_USERNAME);
  await page.fill('input[name="password"], input[type="password"]', STAFF_PASSWORD);
  await page.click('button[type="submit"]');
  await page.waitForURL(/\/staff\/dashboard/);
}

test.describe('User Links Feature', () => {
  test.beforeEach(async ({ page }) => {
    await loginAsStaff(page);
  });

  test('should display Links tab in user modal', async ({ page }) => {
    // Navigate to users page
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Click on first user row to open modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();

    // Wait for modal to appear
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Check that Links tab exists
    const linksTab = page.getByRole('button', { name: /Links/i });
    await expect(linksTab).toBeVisible();
  });

  test('should show Links tab content', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab
    const linksTab = page.getByRole('button', { name: /Links/i });
    await linksTab.click();

    // Verify Links tab content
    await expect(page.getByText('Integration Links')).toBeVisible();
    await expect(page.getByRole('button', { name: /Add Link/i })).toBeVisible();
  });

  test('should open add link form', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab
    await page.getByRole('button', { name: /Links/i }).click();

    // Click Add Link button
    await page.getByRole('button', { name: /Add Link/i }).click();

    // Verify form appears
    await expect(page.getByText('Add New Link')).toBeVisible();
    await expect(page.getByLabel(/Link Type/i)).toBeVisible();
    await expect(page.getByLabel(/Title/i)).toBeVisible();
    await expect(page.getByLabel(/URL/i)).toBeVisible();
    await expect(page.getByLabel(/Description/i)).toBeVisible();
  });

  test('should have all link type options in dropdown', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab and open form
    await page.getByRole('button', { name: /Links/i }).click();
    await page.getByRole('button', { name: /Add Link/i }).click();

    // Check link type dropdown options
    const select = page.locator('select').filter({ hasText: /Knowledge Base|AI Agent/i });
    const options = await select.locator('option').allTextContents();

    // Verify key link types exist
    expect(options.some((opt) => opt.includes('Knowledge Base'))).toBe(true);
    expect(options.some((opt) => opt.includes('AI Agent'))).toBe(true);
    expect(options.some((opt) => opt.includes('AI Voice Agent'))).toBe(true);
    expect(options.some((opt) => opt.includes('WhatsApp'))).toBe(true);
    expect(options.some((opt) => opt.includes('Custom'))).toBe(true);
  });

  test('should validate required fields', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab and open form
    await page.getByRole('button', { name: /Links/i }).click();
    await page.getByRole('button', { name: /Add Link/i }).click();

    // Try to submit without filling required fields
    const addButton = page.getByRole('button', { name: /^Add Link$/i });

    // Button should be disabled when fields are empty
    await expect(addButton).toBeDisabled();
  });

  test('should enable submit button when form is valid', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab and open form
    await page.getByRole('button', { name: /Links/i }).click();
    await page.getByRole('button', { name: /Add Link/i }).click();

    // Fill in required fields
    await page.getByPlaceholder(/Knowledge Base Portal/i).fill('Test Knowledge Base');
    await page.getByPlaceholder(/https/i).fill('https://kb.example.com');

    // Button should now be enabled
    const addButton = page.getByRole('button', { name: /^Add Link$/i });
    await expect(addButton).toBeEnabled();
  });

  test('should cancel form and hide it', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab and open form
    await page.getByRole('button', { name: /Links/i }).click();
    await page.getByRole('button', { name: /Add Link/i }).click();

    // Verify form is visible
    await expect(page.getByText('Add New Link')).toBeVisible();

    // Click Cancel
    await page.getByRole('button', { name: /Cancel/i }).click();

    // Form should be hidden
    await expect(page.getByText('Add New Link')).not.toBeVisible();
  });

  test('should create a new link successfully', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab
    await page.getByRole('button', { name: /Links/i }).click();

    // Click Add Link
    await page.getByRole('button', { name: /Add Link/i }).click();

    // Fill form
    const timestamp = Date.now();
    const testTitle = `E2E Test Link ${timestamp}`;

    // Select link type
    const linkTypeSelect = page.locator('select').first();
    await linkTypeSelect.selectOption('KNOWLEDGE_BASE');

    // Fill title
    await page.getByPlaceholder(/Knowledge Base Portal/i).fill(testTitle);

    // Fill URL
    await page.getByPlaceholder(/https/i).fill(`https://test.example.com/${timestamp}`);

    // Fill description (optional)
    await page.getByPlaceholder(/Brief description/i).fill('E2E test link description');

    // Submit
    await page.getByRole('button', { name: /^Add Link$/i }).click();

    // Wait for success (form should close and link should appear)
    await page.waitForTimeout(2000);

    // Verify link appears in list
    await expect(page.getByText(testTitle)).toBeVisible({ timeout: 5000 });
  });

  test('should show empty state when no links exist', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal for a user without links (if possible)
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab
    await page.getByRole('button', { name: /Links/i }).click();

    // Check for empty state or configured links count
    const linksSection = page.locator('text=Configured Links');
    await expect(linksSection).toBeVisible();
  });

  test('should display link with correct icon', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab
    await page.getByRole('button', { name: /Links/i }).click();

    // If there are links, they should have icons
    const linkItems = page.locator('[class*="flex"][class*="items-center"]').filter({
      hasText: /Knowledge Base|AI Agent|WhatsApp/i,
    });

    const count = await linkItems.count();
    if (count > 0) {
      // Links exist, check they have icons (emoji characters)
      const firstLink = linkItems.first();
      const text = await firstLink.textContent();
      expect(text).toBeTruthy();
    }
  });

  test('should copy link URL to clipboard', async ({ page, context }) => {
    // Grant clipboard permissions
    await context.grantPermissions(['clipboard-read', 'clipboard-write']);

    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab
    await page.getByRole('button', { name: /Links/i }).click();

    // First create a link if none exist
    const configuredLinksText = await page.getByText(/Configured Links/).textContent();

    if (configuredLinksText?.includes('(0)')) {
      // Create a test link first
      await page.getByRole('button', { name: /Add Link/i }).click();
      await page.locator('select').first().selectOption('CUSTOM');
      await page.getByPlaceholder(/Knowledge Base Portal/i).fill('Copy Test Link');
      await page.getByPlaceholder(/https/i).fill('https://copy-test.example.com');
      await page.getByRole('button', { name: /^Add Link$/i }).click();
      await page.waitForTimeout(2000);
    }

    // Find copy button and click it
    const copyButton = page.locator('button[title="Copy URL"]').first();
    if (await copyButton.isVisible()) {
      await copyButton.click();

      // Check for success indicator (checkmark icon appears)
      await page.waitForTimeout(500);
      // The copy button should show a check icon briefly
    }
  });

  test('should delete a link with confirmation', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab
    await page.getByRole('button', { name: /Links/i }).click();

    // First create a link to delete
    await page.getByRole('button', { name: /Add Link/i }).click();
    const timestamp = Date.now();
    await page.locator('select').first().selectOption('CUSTOM');
    await page.getByPlaceholder(/Knowledge Base Portal/i).fill(`Delete Test ${timestamp}`);
    await page.getByPlaceholder(/https/i).fill(`https://delete-test.example.com/${timestamp}`);
    await page.getByRole('button', { name: /^Add Link$/i }).click();
    await page.waitForTimeout(2000);

    // Handle the confirm dialog
    page.on('dialog', async (dialog) => {
      expect(dialog.type()).toBe('confirm');
      await dialog.accept();
    });

    // Click delete button on the newly created link
    const deleteButton = page.locator('button[title="Delete"]').first();
    if (await deleteButton.isVisible()) {
      await deleteButton.click();
      await page.waitForTimeout(1000);
    }
  });

  test('should edit an existing link', async ({ page }) => {
    await page.goto(`${BASE_URL}/staff/dashboard/users`);
    await page.waitForLoadState('networkidle');

    // Open user modal
    const userRow = page.locator('tr').filter({ hasText: '@' }).first();
    await userRow.click();
    await page.waitForSelector('[role="dialog"], .fixed.inset-0');

    // Click Links tab
    await page.getByRole('button', { name: /Links/i }).click();

    // First create a link to edit
    await page.getByRole('button', { name: /Add Link/i }).click();
    const timestamp = Date.now();
    await page.locator('select').first().selectOption('CUSTOM');
    await page.getByPlaceholder(/Knowledge Base Portal/i).fill(`Edit Test ${timestamp}`);
    await page.getByPlaceholder(/https/i).fill(`https://edit-test.example.com/${timestamp}`);
    await page.getByRole('button', { name: /^Add Link$/i }).click();
    await page.waitForTimeout(2000);

    // Click edit button
    const editButton = page.locator('button[title="Edit"]').first();
    if (await editButton.isVisible()) {
      await editButton.click();

      // Form should open with Edit Link title
      await expect(page.getByText('Edit Link')).toBeVisible();

      // Update the title
      await page.getByPlaceholder(/Knowledge Base Portal/i).fill(`Updated ${timestamp}`);

      // Save changes
      await page.getByRole('button', { name: /Update Link/i }).click();
      await page.waitForTimeout(2000);
    }
  });
});

test.describe('User Links API Integration', () => {
  test('API should return 401 without authentication', async ({ request }) => {
    const response = await request.get(`${BASE_URL}/api/staff/users/test-id/links`);
    expect(response.status()).toBe(401);
  });

  test('API should validate URL format', async ({ request }) => {
    const response = await request.post(`${BASE_URL}/api/staff/users/test-id/links`, {
      data: {
        linkType: 'CUSTOM',
        title: 'Test',
        url: 'invalid-url',
      },
    });
    expect([400, 401]).toContain(response.status());
  });
});
