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

/**
 * E2E Test: Complete Ticket Lifecycle
 * 
 * Tests the full user journey from login to ticket resolution.
 */
test.describe('Ticket Lifecycle', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/login');
  });

  test('user can complete full ticket lifecycle', async ({ page }) => {
    await page.route('**/api/v1/auth/request-otp', async (route) => {
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({ message: 'If your email is registered, you will receive a login code shortly.' }),
      });
    });

    await page.route('**/api/v1/auth/verify-otp', async (route) => {
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({
          token: 'e2e-test-token',
          token_type: 'Bearer',
          data: {
            id: '00000000-0000-4000-8000-000000000001',
            name: 'E2E User',
            email: 'e2e@mountainview-eg.com',
            locale: 'en',
            company_id: '00000000-0000-4000-8000-000000000002',
            company: {
              id: '00000000-0000-4000-8000-000000000002',
              name: 'Mountain View',
              domain: 'mountainview-eg.com',
              is_active: true,
              created_at: new Date().toISOString(),
              updated_at: new Date().toISOString(),
            },
            departments: [],
            roles: [],
            permissions: ['department.tickets.view'],
            is_active: true,
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
          },
        }),
      });
    });

    await page.route('**/api/v1/auth/me', async (route) => {
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({
          data: {
            id: '00000000-0000-4000-8000-000000000001',
            name: 'E2E User',
            email: 'e2e@mountainview-eg.com',
            locale: 'en',
            company_id: '00000000-0000-4000-8000-000000000002',
            company: {
              id: '00000000-0000-4000-8000-000000000002',
              name: 'Mountain View',
              domain: 'mountainview-eg.com',
              is_active: true,
              created_at: new Date().toISOString(),
              updated_at: new Date().toISOString(),
            },
            departments: [],
            roles: [],
            permissions: ['department.tickets.view'],
            is_active: true,
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
          },
        }),
      });
    });

    // Step 1: Login with OTP
    await page.getByLabel(/email address/i).fill('e2e@mountainview-eg.com');
    await page.getByRole('button', { name: /send login code/i }).click();
    await page.getByLabel(/login code/i).fill('123456');
    await page.getByRole('button', { name: /verify & sign in/i }).click();
    await expect(page).toHaveURL(/\/dashboard/);

    // Step 2: Navigate to tickets
    await page.getByRole('link', { name: 'Tickets' }).click();
    await expect(page).toHaveURL(/\/tickets/);

    // Step 3: Create new ticket
    await page.getByRole('button', { name: /create ticket/i }).click();
    
    // Fill ticket form
    await page.getByLabel(/subject/i).fill('Test ticket from E2E');
    await page.getByLabel(/description/i).fill('This is a test ticket created by Playwright');
    await page.getByLabel(/priority/i).selectOption('high');
    await page.getByLabel(/category/i).selectOption({ index: 1 });
    
    // Submit form
    await page.getByRole('button', { name: /submit|create/i }).click();
    
    // Verify success message
    await expect(page.getByText(/ticket created successfully/i)).toBeVisible();

    // Step 4: View ticket details
    await page.getByText('Test ticket from E2E').click();
    await expect(page.getByText('Test ticket from E2E')).toBeVisible();
    await expect(page.getByText(/high priority/i)).toBeVisible();

    // Step 5: Add reply
    await page.getByPlaceholder(/type your reply/i).fill('Working on this issue');
    await page.getByRole('button', { name: /submit/i }).click();
    await expect(page.getByText('Working on this issue')).toBeVisible();

    // Step 6: Resolve ticket
    await page.getByRole('button', { name: /resolve|close/i }).click();
    await page.getByRole('button', { name: /confirm/i }).click();
    await expect(page.getByText(/resolved|closed/i)).toBeVisible();
  });

  test('user can search and filter tickets', async ({ page }) => {
    await page.goto('/dashboard');
    
    // Navigate to search
    await page.getByRole('link', { name: /search/i }).click();
    
    // Search for tickets
    await page.getByPlaceholder(/search/i).fill('email');
    await page.getByRole('button', { name: /search/i }).click();
    
    // Verify results
    await expect(page.getByText(/email/i)).toBeVisible();
    
    // Apply filters
    await page.getByLabel(/status/i).selectOption('open');
    await page.getByLabel(/priority/i).selectOption('high');
    await page.getByRole('button', { name: /apply filters/i }).click();
    
    // Verify filtered results
    await expect(page.getByText(/open/i)).toBeVisible();
    await expect(page.getByText(/high/i)).toBeVisible();
  });

  test('theme and language switching works', async ({ page }) => {
    await page.goto('/login');
    
    // Test theme toggle
    const themeButton = page.getByRole('button', { name: /toggle theme|🌙|☀️/ });
    await themeButton.click();
    
    // Verify dark mode applied (check background color)
    const body = page.locator('body');
    const backgroundColor = await body.evaluate(el => 
      window.getComputedStyle(el).backgroundColor
    );
    expect(backgroundColor).not.toBe('rgb(255, 255, 255)');
    
    // Test language toggle
    const langButton = page.getByRole('button', { name: /ع|EN|العربية|English/ });
    await langButton.click();
    
    // Verify RTL applied
    const htmlDir = await page.locator('html').getAttribute('dir');
    expect(['rtl', 'ltr']).toContain(htmlDir);
  });

  test('mobile responsive navigation works', async ({ page }) => {
    // Set mobile viewport
    await page.setViewportSize({ width: 375, height: 667 });
    await page.goto('/dashboard');
    
    // Verify mobile layout
    const sidebar = page.locator('aside');
    const isVisible = await sidebar.isVisible();
    
    // On mobile, sidebar should be hidden by default or collapsible
    expect(isVisible).toBeDefined();
  });

  test('form validation prevents invalid submissions', async ({ page }) => {
    await page.goto('/dashboard');
    await page.getByRole('link', { name: /tickets/i }).click();
    await page.getByRole('button', { name: /create ticket/i }).click();
    
    // Try to submit empty form
    await page.getByRole('button', { name: /submit|create/i }).click();
    
    // Verify validation errors appear
    await expect(page.getByText(/required|field is required/i)).toBeVisible();
  });

  test('unauthorized access is prevented', async ({ page }) => {
    // Try to access protected route without login
    await page.goto('/tickets');
    
    // Should redirect to login
    await expect(page).toHaveURL(/\/login/);
  });
});
