import { test, expect } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';

test.describe('Event Summary Page', () => {
  // Define test variables
  const testTrainerUsername = 'test_trainer';
  const testTrainerPassword = 'Test123!';
  
  // We'll need to figure out a test event ID during the test
  let testEventId: string;
  
  test.beforeEach(async ({ page }) => {
    // Log in before each test
    const loginPage = new LoginPage(page);
    await loginPage.navigate();
    await loginPage.login(testTrainerUsername, testTrainerPassword);
    
    // Navigate to dashboard to find an event to use for testing
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.navigate();
    
    // Find the first event in the dashboard and get its ID
    // We'll extract the event ID from the "Summary" link's href
    const summaryLink = page.locator('.column-actions a:has-text("Summary")').first();
    
    // Check if there's at least one event
    const linkCount = await summaryLink.count();
    if (linkCount === 0) {
      // No events available for testing, we'll need to skip the tests
      test.skip(true, 'No events available for testing');
      return;
    }
    
    // Get the href attribute from the summary link
    const summaryUrl = await summaryLink.getAttribute('href');
    
    // Extract the event ID from the URL
    if (summaryUrl) {
      const match = summaryUrl.match(/event_id=(\d+)/);
      if (match && match[1]) {
        testEventId = match[1];
      } else {
        test.skip(true, 'Could not extract event ID from summary link');
      }
    } else {
      test.skip(true, 'Summary link has no href attribute');
    }
  });
  
  test('should be accessible from dashboard', async ({ page }) => {
    // Navigate to dashboard
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.navigate();
    
    // Find and click the first summary link
    const summaryLink = page.locator('.column-actions a:has-text("Summary")').first();
    await expect(summaryLink).toBeVisible();
    await summaryLink.click();
    
    // Verify we're on the event summary page
    await expect(page).toHaveURL(/.*\/event-summary\/.*event_id=.*/);
    await expect(page.locator('h1')).toContainText('Summary');
  });
  
  test('should display event overview information', async ({ page }) => {
    // Navigate directly to the event summary page
    await page.goto(`/event-summary/?event_id=${testEventId}`);
    
    // Check for event overview section
    await expect(page.locator('h2:has-text("Event Overview")')).toBeVisible();
    
    // Check for basic event details
    const detailsTable = page.locator('.hvac-details-table');
    await expect(detailsTable).toBeVisible();
    
    // Check for specific fields
    const dateRow = detailsTable.locator('tr', { hasText: 'Date & Time' });
    const statusRow = detailsTable.locator('tr', { hasText: 'Status' });
    
    await expect(dateRow).toBeVisible();
    await expect(statusRow).toBeVisible();
  });
  
  test('should display event statistics', async ({ page }) => {
    // Navigate directly to the event summary page
    await page.goto(`/event-summary/?event_id=${testEventId}`);
    
    // Check for statistics section
    await expect(page.locator('h2:has-text("Event Statistics")')).toBeVisible();
    
    // Check for statistics cards
    const statsRow = page.locator('.hvac-stats-row');
    await expect(statsRow).toBeVisible();
    
    // Look for specific metric cards
    const totalTicketsCard = page.locator('.hvac-stat-card h3:has-text("Total Tickets")');
    const totalRevenueCard = page.locator('.hvac-stat-card h3:has-text("Total Revenue")');
    
    await expect(totalTicketsCard).toBeVisible();
    await expect(totalRevenueCard).toBeVisible();
  });
  
  test('should display ticket sales and attendees information', async ({ page }) => {
    // Navigate directly to the event summary page
    await page.goto(`/event-summary/?event_id=${testEventId}`);
    
    // Check for ticket sales section
    await expect(page.locator('h2:has-text("Ticket Sales & Attendees")')).toBeVisible();
    
    // The table might not be visible if there are no attendees, so check for either
    // the table or the "No ticket sales" message
    const attendeesTable = page.locator('.hvac-transactions-table');
    const noAttendeesMessage = page.locator('text=No ticket sales or attendees found');
    
    const hasTable = await attendeesTable.count() > 0;
    if (hasTable) {
      // Check table headers
      const attendeeHeader = attendeesTable.locator('th', { hasText: 'Attendee' });
      const emailHeader = attendeesTable.locator('th', { hasText: 'Email' });
      const ticketTypeHeader = attendeesTable.locator('th', { hasText: 'Ticket Type' });
      
      await expect(attendeeHeader).toBeVisible();
      await expect(emailHeader).toBeVisible();
      await expect(ticketTypeHeader).toBeVisible();
    } else {
      // Check for no attendees message
      await expect(noAttendeesMessage).toBeVisible();
    }
  });
  
  test('should display event description', async ({ page }) => {
    // Navigate directly to the event summary page
    await page.goto(`/event-summary/?event_id=${testEventId}`);
    
    // Check for event description section
    await expect(page.locator('h2:has-text("Event Description")')).toBeVisible();
    
    // Check for description content
    const descriptionContainer = page.locator('.hvac-event-description');
    await expect(descriptionContainer).toBeVisible();
  });
  
  test('should have working navigation links', async ({ page }) => {
    // Navigate directly to the event summary page
    await page.goto(`/event-summary/?event_id=${testEventId}`);
    
    // Check for dashboard navigation link
    const dashboardLink = page.locator('a[href*="/hvac-dashboard/"]');
    await expect(dashboardLink).toBeVisible();
    
    // Check for edit event link (may not be visible if user doesn't have permission)
    const editEventLink = page.locator('a[href*="/manage-event/"]');
    
    // Check for view public page link
    const viewPublicLink = page.locator('a[href*="/event/"]');
    await expect(viewPublicLink).toBeVisible();
  });
  
  test('should be accessible after login', async ({ page }) => {
    // Verify we can access the event summary page since we're already logged in
    await page.goto(`/event-summary/?event_id=${testEventId}`);
    await page.waitForLoadState('networkidle');
    
    // Check for key sections
    const hasH1 = await page.locator('h1:has-text("Summary")').isVisible();
    const hasEventOverview = await page.locator('h2:has-text("Event Overview")').isVisible();
    const hasEventStatistics = await page.locator('h2:has-text("Event Statistics")').isVisible();
    
    // Create screenshot for verification
    await page.screenshot({ path: 'event-summary-logged-in.png' });
    
    // Verify at least some of the elements are visible
    expect(hasH1 || hasEventOverview || hasEventStatistics).toBeTruthy();
  });
  
  test('should prevent unauthorized access', async ({ browser }) => {
    // Create a fresh context with no cookies/session
    const context = await browser.newContext();
    const page = await context.newPage();
    
    // Try to access event summary page when logged out
    await page.goto(`/event-summary/?event_id=${testEventId}`);
    await page.waitForLoadState('networkidle');
    
    // Take a screenshot to verify
    await page.screenshot({ path: 'event-summary-logged-out.png' });
    
    // First, check if we're on the login page
    const onLoginPage = await page.url().includes('/community-login/');
    
    // Check that we're either redirected to the login page or the dashboard
    // Either way, we should NOT see event content
    
    // Verify content elements are NOT visible
    const eventOverview = page.locator('h2:has-text("Event Overview")');
    const eventStatistics = page.locator('h2:has-text("Event Statistics")');
    
    await expect(eventOverview).not.toBeVisible();
    await expect(eventStatistics).not.toBeVisible();
    
    // Clean up
    await context.close();
  });
});