import { test, expect } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
import { CreateEventPage } from './pages/CreateEventPage';
import { EventSummaryPage } from './pages/EventSummaryPage';
import { ModifyEventPage } from './pages/ModifyEventPage';
import { CertificatePage } from './pages/CertificatePage';
import { Config } from './utils/Config';

/**
 * @description Comprehensive trainer journey test that works with latest Playwright
 * @tag @trainer-journey @certificates
 */
test('Complete trainer journey with certificate functionality', async ({ page }) => {
  // Step 1: Login
  const loginPage = new LoginPage(page);
  await loginPage.navigate();
  await loginPage.login(Config.testTrainer.username, Config.testTrainer.password);
  
  // Verify successful login
  await expect(page).toHaveURL(/hvac-dashboard/);
  
  // Step 2: Access dashboard
  const dashboardPage = new DashboardPage(page);
  await dashboardPage.navigate();
  await expect(dashboardPage.isOnDashboard()).resolves.toBeTruthy();
  
  // Step 3: Create a new event
  await dashboardPage.clickCreateEvent();
  
  const createEventPage = new CreateEventPage(page);
  
  // Generate unique event name with timestamp
  const timestamp = new Date().getTime();
  const eventTitle = `Journey Test Event ${timestamp}`;
  
  // Fill required event details
  await createEventPage.fillEventTitle(eventTitle);
  await createEventPage.fillEventDescription(`Test event for trainer journey ${timestamp}`);
  
  // Set dates (30 days in future)
  const futureDate = new Date();
  futureDate.setDate(futureDate.getDate() + 30);
  await createEventPage.setStartDate(futureDate.toLocaleDateString('en-US'));
  await createEventPage.setEndDate(futureDate.toLocaleDateString('en-US'));
  await createEventPage.setStartTime('10:00 AM');
  await createEventPage.setEndTime('4:00 PM');
  
  // Add ticket information
  await createEventPage.addTicket('General Admission', '100');
  
  // Submit the form
  const eventId = await createEventPage.submitForm();
  expect(eventId).toBeTruthy();
  
  // Step 4: Verify event summary
  const eventSummaryPage = new EventSummaryPage(page);
  expect(await eventSummaryPage.isOnEventSummary()).toBeTruthy();
  expect(await eventSummaryPage.getEventTitle()).toBe(eventTitle);
  
  // Step 5: Create test attendees (at least 5)
  await page.waitForTimeout(1000); // Brief pause to ensure page is ready
  
  // Add test attendees via API for efficiency
  for (let i = 1; i <= 5; i++) {
    const attendeeData = {
      name: `Test Attendee ${i}`,
      email: `test${i}@example.com`,
      checkedIn: i <= 3 // Mark first 3 as checked in
    };
    
    // Use API endpoint to add attendee (implementation will depend on your API)
    await page.evaluate(async (data) => {
      const response = await fetch('/wp-json/hvac-ce/v1/add-test-attendee', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          event_id: document.querySelector('[data-event-id]')?.getAttribute('data-event-id'),
          ...data
        }),
      });
      return await response.json();
    }, attendeeData);
  }
  
  // Step 6: Return to dashboard
  await dashboardPage.navigate();
  await expect(dashboardPage.isOnDashboard()).resolves.toBeTruthy();
  
  // Step 7: Generate certificates
  await dashboardPage.clickGenerateCertificates();
  
  const certificatePage = new CertificatePage(page);
  expect(await certificatePage.isGenerateCertificatesPageVisible()).toBeTruthy();
  
  // Select our test event
  await certificatePage.selectEvent(eventTitle);
  
  // Get attendee counts
  const totalAttendees = await certificatePage.getAttendeeCount();
  const checkedInAttendees = await certificatePage.getCheckedInAttendeeCount();
  
  expect(totalAttendees).toBeGreaterThanOrEqual(5);
  expect(checkedInAttendees).toBeGreaterThanOrEqual(3);
  
  // Generate certificates for checked-in attendees
  await certificatePage.selectCheckedInAttendees();
  await certificatePage.generateCertificates();
  
  // Verify success
  expect(await certificatePage.isSuccessMessageVisible()).toBeTruthy();
  
  // Step 8: Manage certificates via reports
  await dashboardPage.navigate();
  await dashboardPage.clickCertificateReports();
  
  expect(await certificatePage.isCertificateReportsPageVisible()).toBeTruthy();
  
  // Filter certificates by event 
  await certificatePage.searchCertificates(eventTitle);
  
  // Verify certificates exist
  const certificateCount = await certificatePage.getCertificateCount();
  expect(certificateCount).toBeGreaterThanOrEqual(3); // At least the checked-in attendees
  
  // Test attendee filtering
  const searchTerm = 'Test Attendee 1';
  await certificatePage.searchAttendee(searchTerm);
  
  // Verify filtered results
  const filteredCount = await certificatePage.getCertificateCount();
  expect(filteredCount).toBeGreaterThanOrEqual(1);
  
  // Test certificate preview if available
  if (filteredCount > 0) {
    await certificatePage.viewCertificate(0);
    
    // Verify preview is visible
    const preview = page.locator('.hvac-certificate-preview');
    await expect(preview).toBeVisible();
    
    // Close preview
    await certificatePage.closePreview();
  }
  
  // Step 9: Return to dashboard to verify event statistics
  await dashboardPage.navigate();
  
  // Check event statistics
  const totalEvents = await dashboardPage.getEventCount();
  expect(totalEvents).toBeGreaterThan(0);
  
  // Success - full journey completed
  console.log('Trainer journey with certificates completed successfully');
});