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

// Full Trainer Journey Including Certificate Functionality
test('Trainer journey with certificate functionality', async ({ page }) => {
  console.log('Starting trainer journey with certificates test...');
  
  try {
    // STEP 1: Login as trainer
    console.log('Step 1: Logging in as trainer...');
    const loginPage = new LoginPage(page);
    await loginPage.navigate();
    await loginPage.login(Config.testTrainer.username, Config.testTrainer.password);
    
    // STEP 2: Navigate to dashboard
    console.log('Step 2: Accessing dashboard...');
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.navigate();
    
    // Verify dashboard is accessible
    const isOnDashboard = await dashboardPage.isOnDashboard();
    expect(isOnDashboard).toBeTruthy();
    
    // STEP 3: Create a new event
    console.log('Step 3: Creating a new event...');
    await dashboardPage.clickCreateEvent();
    
    const createEventPage = new CreateEventPage(page);
    
    // Generate a unique event title with timestamp
    const timestamp = new Date().getTime();
    const eventTitle = `Certificate Journey Test Event ${timestamp}`;
    
    // Fill event details
    await createEventPage.fillEventTitle(eventTitle);
    await createEventPage.fillEventDescription(`This is a test event for trainer journey with certificates ${timestamp}`);
    
    // Set event dates (future dates)
    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
    await createEventPage.addTicket('General Admission', '100');
    
    // Submit the form
    const eventId = await createEventPage.submitForm();
    expect(eventId).toBeTruthy();
    
    console.log(`Event created with ID: ${eventId}`);
    
    // Wait for navigation to Event Summary
    await page.waitForLoadState('networkidle');
    
    // STEP 4: Add test attendees
    console.log('Step 4: Adding test attendees...');
    
    // Use the utility to create test attendees
    const testData = new CertificateTestData(page);
    await testData.createTestAttendees(eventId as string, 6);
    
    // STEP 5: Access dashboard to navigate to Certificate features
    console.log('Step 5: Returning to dashboard...');
    await dashboardPage.navigate();
    
    // STEP 6: Generate certificates
    console.log('Step 6: Generating certificates...');
    await dashboardPage.clickGenerateCertificates();
    
    const certificatePage = new CertificatePage(page);
    
    // Verify we're on generate certificates page
    const onGeneratePage = await certificatePage.isGenerateCertificatesPageVisible();
    expect(onGeneratePage).toBeTruthy();
    
    // Verify page elements
    const pageTitle = await page.title();
    console.log(`Generate Certificates page title: ${pageTitle}`);
    expect(pageTitle).toContain('Generate Certificates');
    
    // Select our test event
    await certificatePage.selectEvent(eventTitle);
    
    // Get attendee counts
    const totalAttendees = await certificatePage.getAttendeeCount();
    const checkedInAttendees = await certificatePage.getCheckedInAttendeeCount();
    
    console.log(`Found ${totalAttendees} total attendees, ${checkedInAttendees} checked in`);
    expect(totalAttendees).toBeGreaterThan(0);
    
    // Try different selection methods
    // First, select checked-in attendees
    if (checkedInAttendees > 0) {
      console.log('Selecting checked-in attendees only...');
      await certificatePage.selectCheckedInAttendees();
      
      // Generate certificates for checked-in attendees
      await certificatePage.generateCertificates();
      
      // Check if successful
      const isSuccessCheckedIn = await certificatePage.isSuccessMessageVisible();
      expect(isSuccessCheckedIn).toBeTruthy();
      
      // Get success message
      const successMessage = await certificatePage.getSuccessMessage();
      console.log(`Success message: ${successMessage}`);
      
      // Return to certificates page
      await dashboardPage.clickGenerateCertificates();
      await certificatePage.selectEvent(eventTitle);
    }
    
    // Now select all attendees
    console.log('Selecting all attendees...');
    await certificatePage.selectAllAttendees();
    
    // Generate certificates for all attendees
    await certificatePage.generateCertificates();
    
    // Check if successful
    const isSuccess = await certificatePage.isSuccessMessageVisible();
    expect(isSuccess).toBeTruthy();
    
    // STEP 7: Manage certificates
    console.log('Step 7: Managing certificates...');
    await dashboardPage.navigate();
    await dashboardPage.clickCertificateReports();
    
    // Verify we're on certificate reports page
    const onReportsPage = await certificatePage.isCertificateReportsPageVisible();
    expect(onReportsPage).toBeTruthy();
    
    // Verify page elements
    const reportsPageTitle = await page.title();
    console.log(`Certificate Reports page title: ${reportsPageTitle}`);
    expect(reportsPageTitle).toContain('Certificate Reports');
    
    // Verify filter form is present
    const filterForm = page.locator('form.hvac-certificate-filters');
    await expect(filterForm).toBeVisible();
    
    // STEP 7a: Test event filtering
    console.log('Step 7a: Testing event filtering...');
    await certificatePage.searchCertificates(eventTitle);
    
    // Verify certificates exist after event filtering
    const certificateCount = await certificatePage.getCertificateCount();
    console.log(`Found ${certificateCount} certificates for event: ${eventTitle}`);
    expect(certificateCount).toBeGreaterThan(0);
    
    // STEP 7b: Test attendee filtering
    console.log('Step 7b: Testing attendee filtering...');
    
    // Testing partial name search
    const searchTerm = 'Test Attendee';
    await certificatePage.searchAttendee(searchTerm);
    
    // Verify certificates exist after attendee filtering
    const nameFilteredCount = await certificatePage.getCertificateCount();
    console.log(`Found ${nameFilteredCount} certificates for attendee search: ${searchTerm}`);
    
    // Reset filters
    await certificatePage.resetFilters();
    console.log('Filters reset');
    
    // Apply event filter again
    await certificatePage.searchCertificates(eventTitle);
    
    // STEP 7c: Test certificate viewing
    console.log('Step 7c: Testing certificate viewing...');
    if (certificateCount > 0) {
      console.log('Viewing certificate...');
      await certificatePage.viewCertificate(0);
      
      // Verify certificate preview is visible
      const preview = page.locator('.hvac-certificate-preview');
      await expect(preview).toBeVisible();
      
      // Close preview
      await certificatePage.closePreview();
      
      // Verify preview is closed
      await expect(preview).not.toBeVisible();
    }
    
    // STEP 8: Advanced certificate management (if supported)
    console.log('Step 8: Testing advanced certificate features...');
    try {
      // Test email delivery (if available)
      const emailButton = page.locator('button:has-text("Email Certificates"), a:has-text("Email Certificates")');
      if (await emailButton.isVisible()) {
        console.log('Email certificates feature detected, testing...');
        // Implementation would depend on the specific UI and functionality
        // Just capture screenshot for now
        await page.screenshot({ path: `${Config.screenshotPath}/email-certificates.png` });
      } else {
        console.log('Email certificates feature not found, skipping...');
      }
      
      // Test certificate revocation (if available)
      const revokeButton = page.locator('button:has-text("Revoke"), a:has-text("Revoke")');
      if (await revokeButton.isVisible()) {
        console.log('Certificate revocation feature detected, testing...');
        // For safety, don't actually revoke during test
        await page.screenshot({ path: `${Config.screenshotPath}/revoke-certificate.png` });
      } else {
        console.log('Certificate revocation feature not found, skipping...');
      }
    } catch (error) {
      console.log(`Advanced certificate features not fully implemented: ${error.message}`);
    }
    
    // STEP 9: Return to dashboard and verify event statistics
    console.log('Step 9: Verifying event statistics...');
    await dashboardPage.navigate();
    
    // Check if event appears in dashboard statistics
    const statsSection = page.locator('.hvac-dashboard-stats');
    if (await statsSection.isVisible()) {
      console.log('Dashboard statistics section is visible');
      
      // Get current event count
      const totalEventsCount = await dashboardPage.getEventCount();
      console.log(`Total events count: ${totalEventsCount}`);
      
      // This should be at least 1 since we created an event
      expect(totalEventsCount).toBeGreaterThan(0);
    } else {
      console.log('Dashboard statistics section not found, skipping...');
    }
  } catch (error) {
    console.error('Error during trainer journey test:', error.message);
    // Take a screenshot for debugging
    await page.screenshot({ path: `${Config.screenshotPath}/error-trainer-journey.png` });
    throw error;
  }
  
  console.log('Trainer journey with certificates completed successfully');
});