/**
 * E2E Tests for Workflow Management
 *
 * Tests user workflows:
 * - Display workflow cards based on tier
 * - Activate AI Agent workflow
 * - Show analytics metrics
 * - Filter conversations by platform
 * - Expand conversation to show messages
 * - tier1 cannot activate tier5 features
 *
 * NOTE: These are Playwright E2E test skeletons
 * Run with: npm run test:e2e -- workflow-management
 */

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

// Test configuration
const BASE_URL = process.env.BASE_URL || 'http://localhost:9000';

// Test credentials
const TEST_TIER1_USER = {
  email: process.env.TEST_TIER1_EMAIL || 'tier1@mawidi.test',
  password: process.env.TEST_TIER1_PASSWORD || 'TestPassword123!',
};

const TEST_TIER2_USER = {
  email: process.env.TEST_TIER2_EMAIL || 'tier2@mawidi.test',
  password: process.env.TEST_TIER2_PASSWORD || 'TestPassword123!',
};

const TEST_TIER5_USER = {
  email: process.env.TEST_TIER5_EMAIL || 'tier5@mawidi.test',
  password: process.env.TEST_TIER5_PASSWORD || 'TestPassword123!',
};

/**
 * Helper: Login to dashboard
 */
async function loginToDashboard(page: Page, email: string, password: string) {
  await page.goto(`${BASE_URL}/en/login`);
  await page.fill('input[name="email"]', email);
  await page.fill('input[name="password"]', password);
  await page.click('button[type="submit"]');

  // Wait for navigation to dashboard
  await page.waitForURL(/.*\/dashboard/, { timeout: 10000 });
}

/**
 * Helper: Navigate to workflows section
 */
async function navigateToWorkflows(page: Page) {
  await page.goto(`${BASE_URL}/en/dashboard`);

  // Find and click workflows tab or section
  const workflowsLink = page.locator('a:has-text("Workflows"), button:has-text("Workflows")').first();
  if (await workflowsLink.isVisible()) {
    await workflowsLink.click();
  }

  // Wait for workflows content to load
  await page.waitForSelector('[data-testid="workflows-container"], .workflows-section', { timeout: 5000 });
}

test.describe('Workflow Management E2E Tests', () => {
  test.describe('Tier-based Workflow Display', () => {
    test('tier1 user should see 3 workflow cards (Starter tier)', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER1_USER.email, TEST_TIER1_USER.password);
      await navigateToWorkflows(page);

      // Check for workflow cards
      const workflowCards = page.locator('[data-testid="workflow-card"], .workflow-card');
      await expect(workflowCards).toHaveCount(3);

      // Verify visible workflows for tier1
      await expect(page.locator('[data-workflow-type="ai_agent"]')).toBeVisible();
      await expect(page.locator('[data-workflow-type="whatsapp"]')).toBeVisible();
      await expect(page.locator('[data-workflow-type="appointments"]')).toBeVisible();

      // Verify tier indicator
      await expect(page.locator('[data-testid="current-tier"]')).toContainText('Starter');
    });

    test('tier2 user should see 7 workflow cards (Professional tier)', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      const workflowCards = page.locator('[data-testid="workflow-card"], .workflow-card');
      await expect(workflowCards).toHaveCount(7);

      // Verify additional tier2 workflows are visible
      await expect(page.locator('[data-workflow-type="quotations"]')).toBeVisible();
      await expect(page.locator('[data-workflow-type="crm"]')).toBeVisible();

      await expect(page.locator('[data-testid="current-tier"]')).toContainText('Professional');
    });

    test('tier5 user should see all 14 workflow cards (Ultimate tier)', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER5_USER.email, TEST_TIER5_USER.password);
      await navigateToWorkflows(page);

      const workflowCards = page.locator('[data-testid="workflow-card"], .workflow-card');
      await expect(workflowCards).toHaveCount(14);

      // Verify tier5-exclusive workflows are visible
      await expect(page.locator('[data-workflow-type="lead_generation"]')).toBeVisible();
      await expect(page.locator('[data-workflow-type="lead_scoring"]')).toBeVisible();

      await expect(page.locator('[data-testid="current-tier"]')).toContainText('Ultimate');
    });

    test('should show upgrade prompt for locked workflows', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER1_USER.email, TEST_TIER1_USER.password);
      await navigateToWorkflows(page);

      // Look for locked workflow indicator
      const lockedWorkflow = page.locator('[data-workflow-locked="true"]').first();

      if (await lockedWorkflow.isVisible()) {
        await lockedWorkflow.click();

        // Should show upgrade modal or message
        await expect(
          page.locator('[data-testid="upgrade-modal"], .upgrade-prompt')
        ).toBeVisible();

        await expect(page.locator('text=/upgrade.*tier/i')).toBeVisible();
      }
    });
  });

  test.describe('AI Agent Workflow Activation', () => {
    test('should activate AI Agent workflow successfully', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      // Find AI Agent workflow card
      const aiAgentCard = page.locator('[data-workflow-type="ai_agent"]');
      await expect(aiAgentCard).toBeVisible();

      // Check if already active
      const isActive = await aiAgentCard.locator('[data-status="active"]').count() > 0;

      if (!isActive) {
        // Click activate button
        await aiAgentCard.locator('button:has-text("Activate"), [data-testid="activate-btn"]').click();

        // Wait for activation
        await page.waitForSelector('[data-status="active"]', { timeout: 5000 });

        // Verify success message
        await expect(page.locator('[data-testid="success-toast"], .toast-success')).toBeVisible();
      }

      // Verify status changed
      await expect(aiAgentCard.locator('[data-status="active"]')).toBeVisible();
    });

    test('should deactivate AI Agent workflow', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      const aiAgentCard = page.locator('[data-workflow-type="ai_agent"]');

      // Ensure it's active first
      const isActive = await aiAgentCard.locator('[data-status="active"]').count() > 0;

      if (isActive) {
        // Click deactivate button
        await aiAgentCard.locator('button:has-text("Deactivate"), [data-testid="deactivate-btn"]').click();

        // Confirm if modal appears
        const confirmButton = page.locator('button:has-text("Confirm"), [data-testid="confirm-deactivate"]');
        if (await confirmButton.isVisible({ timeout: 2000 })) {
          await confirmButton.click();
        }

        // Wait for deactivation
        await page.waitForSelector('[data-status="inactive"]', { timeout: 5000 });
      }

      // Verify status changed
      await expect(aiAgentCard.locator('[data-status="inactive"]')).toBeVisible();
    });

    test('should configure AI Agent workflow settings', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      const aiAgentCard = page.locator('[data-workflow-type="ai_agent"]');

      // Click settings/configure button
      await aiAgentCard.locator('button:has-text("Configure"), [data-testid="configure-btn"]').click();

      // Wait for config modal
      await expect(page.locator('[data-testid="workflow-config-modal"]')).toBeVisible();

      // Fill in configuration
      await page.fill('[name="greeting"]', 'Welcome to Mawidi!');
      await page.fill('[name="apiKey"]', 'sk-test-api-key-12345');

      // Save configuration
      await page.click('button:has-text("Save"), [data-testid="save-config"]');

      // Verify success
      await expect(page.locator('[data-testid="success-toast"]')).toBeVisible();
    });
  });

  test.describe('Analytics and Metrics', () => {
    test('should display workflow analytics dashboard', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      // Navigate to analytics section
      const analyticsTab = page.locator('[data-testid="analytics-tab"], a:has-text("Analytics")');
      if (await analyticsTab.isVisible()) {
        await analyticsTab.click();
      }

      // Wait for metrics to load
      await page.waitForSelector('[data-testid="workflow-metrics"], .metrics-container', { timeout: 5000 });

      // Verify key metrics are visible
      await expect(page.locator('[data-metric="total-conversations"]')).toBeVisible();
      await expect(page.locator('[data-metric="active-workflows"]')).toBeVisible();
      await expect(page.locator('[data-metric="messages-sent"]')).toBeVisible();
      await expect(page.locator('[data-metric="messages-received"]')).toBeVisible();
    });

    test('should show daily statistics chart', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      // Look for chart or graph element
      const statsChart = page.locator('[data-testid="stats-chart"], .chart-container, canvas');

      if (await statsChart.first().isVisible({ timeout: 3000 })) {
        await expect(statsChart.first()).toBeVisible();
      }
    });

    test('should filter analytics by date range', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      // Look for date range picker
      const dateRangePicker = page.locator('[data-testid="date-range-picker"], input[type="date"]').first();

      if (await dateRangePicker.isVisible({ timeout: 3000 })) {
        await dateRangePicker.click();

        // Select last 7 days or custom range
        const last7DaysOption = page.locator('text=/last 7 days/i');
        if (await last7DaysOption.isVisible({ timeout: 2000 })) {
          await last7DaysOption.click();

          // Wait for data to refresh
          await page.waitForTimeout(1000);
        }
      }
    });
  });

  test.describe('Conversation Management', () => {
    test('should display conversation list', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      // Navigate to conversations
      const conversationsTab = page.locator('[data-testid="conversations-tab"], a:has-text("Conversations")');
      if (await conversationsTab.isVisible()) {
        await conversationsTab.click();
      }

      // Wait for conversation list
      await page.waitForSelector('[data-testid="conversation-list"], .conversations-container', { timeout: 5000 });

      // Verify conversations are displayed
      const conversations = page.locator('[data-testid="conversation-item"], .conversation-item');
      const count = await conversations.count();

      if (count > 0) {
        await expect(conversations.first()).toBeVisible();
      }
    });

    test('should filter conversations by platform', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      // Navigate to conversations
      const conversationsTab = page.locator('[data-testid="conversations-tab"]');
      if (await conversationsTab.isVisible({ timeout: 2000 })) {
        await conversationsTab.click();
      }

      // Find platform filter
      const platformFilter = page.locator('[data-testid="platform-filter"], select[name="platform"]');

      if (await platformFilter.isVisible({ timeout: 3000 })) {
        // Select WhatsApp platform
        await platformFilter.selectOption('whatsapp');

        // Wait for filtered results
        await page.waitForTimeout(1000);

        // Verify filtered conversations
        const conversations = page.locator('[data-platform="whatsapp"]');
        if (await conversations.first().isVisible({ timeout: 2000 })) {
          await expect(conversations.first()).toBeVisible();
        }
      }
    });

    test('should expand conversation to show messages', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      // Navigate to conversations
      const conversationsTab = page.locator('[data-testid="conversations-tab"]');
      if (await conversationsTab.isVisible({ timeout: 2000 })) {
        await conversationsTab.click();
      }

      // Click on first conversation
      const firstConversation = page.locator('[data-testid="conversation-item"]').first();

      if (await firstConversation.isVisible({ timeout: 3000 })) {
        await firstConversation.click();

        // Wait for messages to appear
        await page.waitForSelector('[data-testid="message-list"], .messages-container', { timeout: 3000 });

        // Verify messages are displayed
        const messages = page.locator('[data-testid="message-item"], .message');
        const messageCount = await messages.count();

        if (messageCount > 0) {
          await expect(messages.first()).toBeVisible();
        }
      }
    });

    test('should show conversation metadata', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      const conversationsTab = page.locator('[data-testid="conversations-tab"]');
      if (await conversationsTab.isVisible({ timeout: 2000 })) {
        await conversationsTab.click();
      }

      const firstConversation = page.locator('[data-testid="conversation-item"]').first();

      if (await firstConversation.isVisible({ timeout: 3000 })) {
        await firstConversation.click();

        // Check for metadata fields
        const metadata = page.locator('[data-testid="conversation-metadata"]');

        if (await metadata.isVisible({ timeout: 2000 })) {
          // Verify metadata fields
          await expect(
            page.locator('[data-testid="customer-name"], [data-testid="customer-phone"]')
          ).toBeTruthy();
        }
      }
    });
  });

  test.describe('Tier Restrictions', () => {
    test('tier1 user cannot activate tier5 features', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER1_USER.email, TEST_TIER1_USER.password);
      await navigateToWorkflows(page);

      // Look for tier5 workflow (lead_generation)
      const leadGenWorkflow = page.locator('[data-workflow-type="lead_generation"]');

      if (await leadGenWorkflow.isVisible({ timeout: 3000 })) {
        // Should be locked
        await expect(leadGenWorkflow.locator('[data-locked="true"]')).toBeVisible();

        // Click should show upgrade prompt
        await leadGenWorkflow.click();

        await expect(
          page.locator('[data-testid="upgrade-modal"], text=/upgrade.*ultimate/i')
        ).toBeVisible();
      }
    });

    test('tier1 user cannot activate voice_agent (tier3 feature)', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER1_USER.email, TEST_TIER1_USER.password);
      await navigateToWorkflows(page);

      const voiceAgentWorkflow = page.locator('[data-workflow-type="voice_agent"]');

      if (await voiceAgentWorkflow.isVisible({ timeout: 3000 })) {
        await expect(voiceAgentWorkflow.locator('[data-locked="true"]')).toBeVisible();

        await voiceAgentWorkflow.click();

        // Should mention tier3/Business upgrade
        await expect(page.locator('text=/upgrade.*business/i')).toBeVisible();
      }
    });

    test('tier2 user can activate tier1 and tier2 features', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      // tier2 workflows should be unlocked
      const tier2Workflows = [
        'ai_agent',
        'whatsapp',
        'appointments',
        'quotations',
        'crm',
      ];

      for (const workflowType of tier2Workflows) {
        const workflow = page.locator(`[data-workflow-type="${workflowType}"]`);

        if (await workflow.isVisible({ timeout: 2000 })) {
          // Should NOT be locked
          const lockedCount = await workflow.locator('[data-locked="true"]').count();
          expect(lockedCount).toBe(0);
        }
      }
    });

    test('tier5 user can activate all features', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER5_USER.email, TEST_TIER5_USER.password);
      await navigateToWorkflows(page);

      // All workflows should be unlocked
      const allWorkflows = page.locator('[data-testid="workflow-card"]');
      const count = await allWorkflows.count();

      for (let i = 0; i < count; i++) {
        const workflow = allWorkflows.nth(i);
        const lockedCount = await workflow.locator('[data-locked="true"]').count();
        expect(lockedCount).toBe(0);
      }
    });
  });

  test.describe('Error Handling', () => {
    test('should show error message when activation fails', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      // Simulate network failure
      await page.route('**/api/dashboard/workflows/**', route => {
        route.fulfill({ status: 500, body: 'Server error' });
      });

      const aiAgentCard = page.locator('[data-workflow-type="ai_agent"]');

      if (await aiAgentCard.isVisible()) {
        await aiAgentCard.locator('button:has-text("Activate")').click();

        // Should show error toast
        await expect(page.locator('[data-testid="error-toast"], .toast-error')).toBeVisible();
      }
    });

    test('should handle session timeout gracefully', async ({ page }) => {
      await loginToDashboard(page, TEST_TIER2_USER.email, TEST_TIER2_USER.password);
      await navigateToWorkflows(page);

      // Clear session cookies
      await page.context().clearCookies();

      // Try to perform action
      const aiAgentCard = page.locator('[data-workflow-type="ai_agent"]');

      if (await aiAgentCard.isVisible()) {
        await aiAgentCard.locator('button').first().click();

        // Should redirect to login or show auth error
        await page.waitForURL(/.*\/(login|auth)/, { timeout: 5000 });
      }
    });
  });
});
